c#高效反射调用方法类
1.创建一个业务类(homeservice),在类下创建3个方法
2.正常方式调用类的方法
3.反射方式调用类的方法
4.调用代码
5.调用结果
6.service类方法代码
内容扩展:
1、正常方式调用类的方法
1
2
3
4
5
6
7
8
9
10
11
12
13
|
/// <summary> /// 正常调用类的方法(parm1) /// </summary> /// <returns></returns> public string getnormalmethod_2() { homeservice service = new homeservice(); //调用有参方法(name) string result = service.sayhello( "李天" ); //输出调用信息 string strs = getinvokeinfo( "sayhello(string name)" , result); return strs; } |
2、反射方式调用类的方法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
/// <summary> /// 通过反射调用类的方法(sayhello(string name)) /// </summary> public string getinvokemethod_2() { // 1.load(命名空间名称),gettype(命名空间.类名) type type = assembly.load( "studyinvokemethod" ).gettype( "studyinvokemethod.homeservice" ); //2.getmethod(需要调用的方法名称) methodinfo method = type.getmethod( "sayhello" , new type[] { typeof ( string ) }); // 3.调用的实例化方法(非静态方法)需要创建类型的一个实例 object obj = activator.createinstance(type); //4.方法需要传入的参数 object [] parameters = new object [] { "李天" }; // 5.调用方法,如果调用的是一个静态方法,就不需要第3步(创建类型的实例) // 相应地调用静态方法时,invoke的第一个参数为null string result = ( string )method.invoke(obj, parameters); //输出调用信息 string strs = getinvokeinfo( "sayhello(string name)" , result); return strs; } |