C#利用反射,遍歷得到一個類的全部屬性名,以及該類的實例的全部屬性的值
總結:
對應某個類的實例化的對象tc, 遍歷獲取全部屬性(子成員)的方法(採用反射):
java
Type t = tc.GetType();//得到該類的Type //再用Type.GetProperties得到PropertyInfo[],而後就能夠用foreach 遍歷了 foreach (PropertyInfo pi in t.GetProperties { object value1 = pi.GetValue(tc, null));//用pi.GetValue得到值 string name = pi.Name;//得到屬性的名字,後面就能夠根據名字判斷來進行些本身想要的操做 //得到屬性的類型,進行判斷而後進行之後的操做,例如判斷得到的屬性是整數 if(value1.GetType() == typeof(int)) { //進行你想要的操做 } }
注意:
必需要設置了get 和set方法的屬性,反射才能得到該屬性
c#
public int Pid { get { return pid; } set { pid = value; } }