反射


Warning: Undefined array key "HTTP_REFERER" in /www/wwwroot/prod/www.enjoyasp.net/wp-content/plugins/google-highlight/google-hilite.php on line 58

1,//调用Type类的静态方法GetType,并将Type对象引用返回给tp变量
Type tp = Type.GetType(“ClassA”, false, false);
//tp对象调用GetMethods方法,返回对象中所有公共方法数组,并赋值给ma数组
MethodInfo[] ma = tp.GetMethods();
Console.WriteLine(“\n\t=================ClassA类所含的方法=================”);
//遍历ma数组中的所有MethodInfo类型子项
foreach (MethodInfo s in ma){
//依次输出MethodInfo类型子项的属性值
Console.WriteLine(“\n\t【{0}方法】”, s.Name);
Console.Write(“方法所属类名称:【{0}】”, s.DeclaringType);
Console.WriteLine(“\t方法是否为构造函数:【{0}】”, s.IsConstructor);
Console.Write(“方法是否为public成员:【{0}】”, s.IsPublic);
Console.WriteLine(“\t方法是否为internal成员:【{0}】”, s.IsAssembly);
Console.Write(“方法是否为protected成员:【{0}】”, s.IsFamily);
Console.WriteLine(“\t方法是否为private成员:【{0}】”, s.IsPrivate);
Console.Write(“方法是否为泛型方法:【{0}】”, s.IsGenericMethod);
Console.WriteLine(“\t方法是否为静态方法:【{0}】”, s.IsStatic);
Console.Write(“方法是否为virtual方法:【{0}】”, s.IsVirtual);
Console.WriteLine(“\t方法返回类型为:【{0}】”, s.ReturnType);

//调用s的GetParameters方法,返回ParameterInfo类型数组//遍历数组的ParameterInfo类型子项
foreach (ParameterInfo pms in s.GetParameters()){//输出ParameterInfo类型子项的属性
Console.WriteLine(“\n\t——【{0}参数】——“, pms.Name);
Console.Write(“参数类型:【{0}】”, pms.ParameterType);
Console.WriteLine(“\t参数位置:【{0}】”, pms.Position);
}
}??

注:当跨项目引用dll时要采用如下形式:
Assembly asmb = Assembly.LoadFrom(“EnterpriseServerBase.dll”) ;
Type supType = asmb.GetType(“EnterpriseServerBase.DataAccess.IDBAccesser”) ;
?
或者在当前项目已经引用目标dll的情况下采用:
Type supType = typeof(BNameSpace.SubSpace.Class);

2,得到所有属性
? Type type = typeof(T);???? System.Reflection.PropertyInfo[] properties = type.GetProperties();
//可用 properties[i].SetValue(t, dr[properties[i].Name], null); 赋值

3,创建对象实例
?T t = Activator.CreateInstance<T>();??
或者:Type type = typeof(T);????? T t = Activator.CreateInstance(type);

4,调用方法:
Assembly asmb = Assembly.LoadFrom(“LvShouSecurity.dll”);
//Type supType = asmb.GetType(“LvShouSecurity.SecurityMan”);
MethodInfo m = asmb.GetType(“LvShouSecurity.SecurityMan”).GetMethod(“Encrypto”);
Object ret = m.Invoke(null, new object[]{“hello”});