1. 程式人生 > >反射獲取物件中屬性的資訊,包括屬性的特性

反射獲取物件中屬性的資訊,包括屬性的特性

/********************************************/
反射獲取物件的屬性資訊
Type T = obj.GetType();//其中obj為一個類的物件
PropertyInfo[] infos = T.GetProperyies();//info裡面儲存了obj物件的各個屬性資訊
foreach(PropertyInfo info in infos)//info裡面是某一個屬性
{
//獲取該屬性具有的特性,Atts實際上是一個特性陣列,裡面包含了該屬性的所有特性
var Atts = propertyInfo.GetCustomAttributes(true);
//獲取特性的型別
Type AttType =Atts [i].GetType();//或者獲取它的名字 Atts [index].GetType().Name
//Atts [i]是一個object型別,需要強制型別轉換才能,如:
XmlAttribute xAtt = (XmlAttribute)Atts [i]
//然後就可以獲取該屬性的該特性中的值了
string eleName = xAtt.ElementName;
/*******

獲取屬性的值**************/
object propertyValue = propertyInfo.GetValue(obj, null);//你得知道它是什麼型別,再強制型別轉換

}