利用反射动态从程序集执行方法和属性

程序结构:

//获取程序集
Assembly asb = Assembly.LoadFrom(path);//path为程序集的物理路径
//获取程序集下面的Student类
Type document = asb.GetType("DAL.Student");//参数必须是命名空间+类名,否则会报错。
//实例化Document类对象(有参数的话需要传递object参数)
object docObj = Activator.CreateInstance(document);
//获取Document类中的方法
MethodInfo mi = document.GetMethod("GetStudentName");
//参数
object[] parameter = new object[] { "李四" };
string s= mi.Invoke(docObj, parameter).ToString();//输出方法的返回值:李四
FieldInfo pi = document.GetField("Name");//获取Document类中的属性
string name= pi.GetValue(docObj).ToString();//输出方法的属性:张三

2. // 静态方法的调用

method = type.GetMethod("WriteName");//获得静态方法的名称

s = (string)method.Invoke(null,new string[]{"jianglijun"});//第一个参数为null,因为是静态的。第二个是方法的参数。是object数组。


3.//无参数的实例方法

method = type.GetMethod("无参方法名称");

s = (string)method.Invoke(obj,null);

4.给封装属性赋值

System.Reflection.PropertyInfo propertyInfo = type.GetProperty("属性名称"); //获取指定名称的属性
int value_Old = (int)propertyInfo.GetValue(obj, null); //获取属性值。第一个参数是对应类的实例
Console.WriteLine(value_Old);
propertyInfo.SetValue(obj, 5, null); //给对应属性赋值。第一个类是对应类的实例。

原文地址:https://www.cnblogs.com/zt666/p/6273520.html