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);
反射有很多少实际应用,待续.................................