通常用到的方法是通過反射進行獲取:
例如有如下Student類:
public class Student { private string id; public string Id { get { return id; } set { id = value; } } private string name; public string Name { get { return name; } set { name = value; } } private string age; public string Age { get { return age; } set { age = value; } } }
需要添加的命名空間:
using System.Reflection;
具體的反射方法如下所示:
private PropertyInfo[] GetPropertyInfoArray() { PropertyInfo[] props = null; try { Type type = typeof(EricSunApp.Student); object obj = Activator.CreateInstance(type); props = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); } catch (Exception ex) { } return props; }
之后就是對返回來的數組進行遍歷了。
獲取一個類中所有的字段也是類似的方法:
可以再上網查一下關於反射的更多知識。。。。
