using System.Reflection;
反射就是動態加載程序集的元數據
反射有兩種方式
第一種
直接 把對像反射
Type t=Typeof(對像)
第二種
從程序集加載
Assembly asm = Assembly.LoadFile(path);
得到是一個集合
List<Type> li = new List<Type>();
li = asm.GetTypes().ToList<Type>();
反射後,怎麼得到對像
方法
#region 反射類的方法
////反射類
//Type t1 = asm.GetType("lib.Person");
////得到這個類的方法
//MethodInfo met = t1.GetMethod("Center");
////創建這個方法的對像
//object o = Activator.CreateInstance(t1);
////引用這個方法
//MessageBox.Show(met.Invoke(o,new string[]{"123"}).ToString());
#endregion
屬性
#region 反射類的屬性
//反射類
Type t1 = asm.GetType("lib.Person");
//得到這個類的屬性
PropertyInfo prt = t1.GetProperty("Name");
object o = Activator.CreateInstance(t1);
MessageBox.Show(prt.GetValue(o,null).ToString());
//獲取屬性,和值
foreach (PropertyInfo item in type.GetProperties())
{
XElement xe = new XElement(item.Name.ToString(), item.GetValue(obj, null).ToString());
root.Add(xe);
}
#endregion
特性
//獲取特性值;
object[] o = item.GetCustomAttributes(typeof(ZdyarriAttribute),false);
XElement xe = new XElement(item.Name.ToString(), item.GetValue(obj, null).ToString());
XAttribute xa = new XAttribute("中文",((ZdyarriAttribute)o[0]).DisZdyarri.ToString());
反射常用的一些方法
開始反射
Type t1 = asm.GetType("lib.Person");
List<Type> li = new List<Type>();
li = asm.GetTypes().ToList<Type>();
方法
MethodInfo met = t1.GetMethod("Center");
MethodInfo[] met=item.GetMethods()
屬性
PropertyInfo prt = t1.GetProperty("Name");
PropertyInfo[] prt = t1.GetPropertys();
判讀
IsSubclassOf 判斷前面的是不是後面的子類;
T.IsSubclassOf(T1)
IsAssignableFrom 判斷後面的是不是前面的子類
IsInstanceOfType 驗證後面的對像是不是前面類型的實例
獲取自定義標識屬性
object[] objAttrs = property.GetCustomAttributes(typeof(CanNotSerializableAttribute), false);
object[] objj = item.GetCustomAttributes(typeof(TnameAttribute), false);
反射有很多少實際應用,待續.................................