定义和执行动态的方法:
1 public class Test
2 {
3 private bool m_IsRun;//设备运行状态
4 public bool StartRun(string userName)
5 {
6 Console.WriteLine("Device:启动,操作员:{0}", userName);
7 if (m_IsRun)
8 {
9 Console.WriteLine("Device:设备已经在运行");
10 return false;
11 }
12 else
13 {
14 m_IsRun = true;
15 Console.WriteLine("Device:设备已成功启动");
16 return true;
17 }
18 }
19 protected bool StopRun(string userName)
20 {
21 Console.WriteLine("Device:停止设备操作,操作员:{0}", userName);
22 if (!m_IsRun)
23 {
24 Console.WriteLine("Device:设备已纪停止,不能重复停止");
25 return false;
26 }
27 else
28 {
29 m_IsRun = false;
30 Console.WriteLine("Device:设备已纪成功停止");
31 return true;
32 }
33 }
34 }
35 class Program
36 {
37 static void Main(string[] args)
38 {
39 Test test = new Test();
40 //获取类型信息
41 Type objType = test.GetType();
42 //获取StartRun方法
43 MethodInfo info = objType.GetMethod("StartRun");
44 if (info == null)
45 {
46 Console.WriteLine("获取方法失败");
47 Console.ReadKey();
48 return;
49 }
50 Console.WriteLine("调用方法");
51 //下面这句代码相当于bool ret=test.StartRun("李四");
52 bool ret = (bool)info.Invoke(test, new object[] { "李四" });
53 if (ret)
54 Console.WriteLine("启动成功");
55 else
56 Console.WriteLine("启动失败");
57 Console.ReadKey();
58 }
59 }
(待续)