C#利用反射动态调用类及方法

此方法可以用于未明确类名及方法名,通过对动态获取到存储在变量中的类和方法进行访问

 

string className = "Class1";//类名称
string strClass = "ConsoleApplication1." + className;  //命名空间+类名  注意:类不可以是抽象类,否则无法创建
string strMethod = "test";//方法名
Type type;
object objs;
//通过string类型的strClass获得同名类“type”
type = Type.GetType(strClass);

//创建type类的实例 "objs"
objs = System.Activator.CreateInstance(type);

//加载需要访问的方法,如果有参数的可以设置传参Type[]中是参数的个数和类型,可根据实际调用的方法定义,无参方法GetMethod中只填写类名变量即可
MethodInfo method = type.GetMethod(strMethod, new Type[] { typeof(string), typeof(string) });

//使用指定参数调用由当前实例表示的方法或构造函数。
method.Invoke(objs, new object[] { "参数1", "参数2" });

 

posted @ 2022-01-18 10:13  小飛  阅读(557)  评论(0编辑  收藏  举报