反射与委托(简单实例)
闲来无事,写了一段 反射与委托的 Demo。
我尽量加了注释,
希望能给还不太了解反射与委托的朋友以启示。
![]()
![]()
![]()
![]()
![]()
![]()
![]()
1
using System;2
using System.Collections.Generic;3
using System.Linq;4
using System.Text;5
using System.Reflection;6

7
namespace ThreadDemo8


{9

/**//// <summary>10
/// 反射实例11
/// </summary>12
class Reflection13

{14
static void Main(string[] args)15

{16
Assembly asm = Assembly.Load("ThreadDemo");//加载程序集17
Type[] typeInfo = asm.GetTypes();//获取程序集类型数组18
foreach (Type types in typeInfo)19

{20
Console.WriteLine("程序集中类型:{0}", types.Name);21
MethodInfo[] mInfo = types.GetMethods();22
foreach (MethodInfo information in mInfo)23

{24
Console.WriteLine("此类型所有的方法:{0}", information.Name);25
}26
Console.WriteLine("\n");27
}28
Console.WriteLine("\n\n");29
Console.WriteLine("开始!");30

31
Type inType = typeof(ThreadTest);32
object obj = Activator.CreateInstance(inType);33

string[] s =
{ "mlg" };//方法的参数34
object objName = Activator.CreateInstance(inType, s);//创建指定类型的实例35

36
MethodInfo methodInfo = inType.GetMethod("ThreadMethod");//根据字符串来获取方法信息37
// methodInfo.Invoke(obj, null);38
methodInfo.Invoke(objName, null);//调用类型中的方法39
Console.ReadLine();40

41
}42
}43
}44

45

1 namespace ThreadDemo
2 {
3 /// <summary>
4 /// 委托
5 /// </summary>
6 class Delegate
7 {
8 public delegate int testDelegate(int i,int j);//定义委托类型
9 static void Main(string[] args)
10 {
11 Delegate d = new Delegate();
12 d.DataInfo();
13 }
14 public void getDeltegate(testDelegate dg,int i,int j)//委托类型的传参
15 {
16 Console.WriteLine(dg(i,j).ToString());//调用被委托的方法
17 Console.ReadLine();
18 }
19 /// <summary>
20 /// 动态调用委托
21 /// </summary>
22 public void DataInfo()
23 {
24 //调用委托
25 getDeltegate(new testDelegate(DelegateInfor),2,3);
26 getDeltegate(new testDelegate(DelegateInfor2),1,1);
27 getDeltegate(new testDelegate(DelegateInfor3),-1,-1);
28 }
29
30 public int DelegateInfor(int i,int j)
31 {
32 return i+j;
33 }
34 public int DelegateInfor2(int i, int j)
35 {
36 return i + j;
37 }
38 public int DelegateInfor3(int i, int j)
39 {
40 return i + j;
41 }
42 }
以上两段实例,代码量较少,但是麻雀虽小,五脏俱全。
全当作参考资料吧。
浙公网安备 33010602011771号