c#利用反射Assembly 对类和成员属性进行操作

protected static void test()
{
//获取程序集
Assembly assembly = System.Reflection.Assembly.GetExecutingAssembly();//Assembly.LoadFrom("test.dll"); //获取模块
Module[] modules = assembly.GetModules();
foreach (Module module in modules)
{
Console.WriteLine("module name:" + module.Name);
} //获取类
Type type = assembly.GetType("Reflect_test.PurchaseOrderHeadManageModel", true, true); //命名空间名称 + 类名 //创建类的实例
object obj = Activator.CreateInstance(type, true); //获取私有字段
FieldInfo[] myfields = type.GetFields(BindingFlags.NonPublic | BindingFlags.IgnoreCase | BindingFlags.Instance);
for (int i = ; i < myfields.Length; i++)
{
Console.WriteLine("字段名:{0},类型:{1}", myfields[i].Name, myfields[i].FieldType);
} //获取公共属性
PropertyInfo[] Propertys = type.GetProperties();
for (int i = ; i < Propertys.Length; i++)
{
// Propertys[i].SetValue(Propertys[i], i, null); //设置值
// Propertys[i].GetValue(Propertys[i],null); //获取值
Console.WriteLine("属性名:{0},类型:{1}",Propertys[i].Name,Propertys[i].PropertyType);
} //构造函数集合
ConstructorInfo[] myconstructors = type.GetConstructors();
foreach (ConstructorInfo csinfo in myconstructors)
{
Console.WriteLine("ConstructorInfo:{0}",csinfo.Name);
foreach (ParameterInfo pinfo in csinfo.GetParameters())//构造函数参数列表
{
Console.WriteLine("Parameter:{0},{1}", pinfo.Name,pinfo.ParameterType);
}
}
//公共方法,包括属性
MethodInfo[] methods = type.GetMethods();
foreach (MethodInfo method in methods)
{
//IsSpecialName:是否是属性
if (!method.IsSpecialName)
{
// Console.WriteLine("类型:" + method.Attributes);
Console.WriteLine("method name:" + method.Name);
}
} //调用静态方法
int result = (int)type.InvokeMember("StaticPlus", BindingFlags.InvokeMethod, null, null, new object[] {, });
Console.WriteLine("调用静态方法-结果是:{0}",result); //调用非静态方法
result = (int)type.InvokeMember("Plus", BindingFlags.InvokeMethod, null, obj, new object[] { , });
Console.WriteLine("调用非静态方法-结果是:{0}",result); EventInfo[] Myevents=type.GetEvents();
foreach (EventInfo einfo in Myevents)
{
Console.WriteLine("事件:{0}", einfo.Name);
}
}
上一篇:vue项目分辨率


下一篇:关于 Unity 项目中的 Mono 堆内存泄露