25.什么是反射?
答:
反射,Reflection,通过它我们可以在运行时获得各种信息,如程序集、模块、类型、字段、属性、方法和事件
通过对类型动态实例化后,还可以对其执行操作
简单来说就是用string可以在runtime为所欲为的东西,实际上就是一个.net framework内建的万能工厂
一般用于插件式框架程序和设计模式的实现,当然反射是一种手段可以充分发挥其能量来完成你想做的任何事情(前面好象见过一位高人用反射调用一个官方类库中未说明的函数。。。)
示例:
1using System;
2using System.Collections.Generic;
3using System.Text;
4
5namespace Example25Lib
6{
7 public class Class1
8 {
9 private string name;
10 private int age;
11
12 //如果显式的声明了无参数构造函数,客户端只需要用程序集的CreateInstance即可实例化该类
13 //在此特意不实现,以便在客户调用端体现构造函数的反射实现
14 //public Class1()
15 //{
16 //}
17 public Class1(string Name, int Age)
18 {
19 name = Name;
20 age = Age;
21 }
22 public void ChangeName(string NewName)
23 {
24 name = NewName;
25 }
26 public void ChangeAge(int NewAge)
27 {
28 age = NewAge;
29 }
30 public override string ToString()
31 {
32 return string.Format("Name: {0}, Age: {1}", name, age);
33 }
34 }
35}
反射实例化对象并调用其方法,属性和事件的反射调用略去
1using System;
2using System.Collections.Generic;
3using System.Text;
4
5//注意添加该反射的命名空间
6using System.Reflection;
7
8namespace Example25
9{
10 class Program
11 {
12 static void Main(string[] args)
13 {
14 //加载程序集
15 Assembly tmpAss = Assembly.LoadFile(AppDomain.CurrentDomain.BaseDirectory + "Example25Lib.dll");
16
17 //遍历程序集内所有的类型,并实例化
18 Type[] tmpTypes = tmpAss.GetTypes();
19 foreach (Type tmpType in tmpTypes)
20 {
21 //获取第一个类型的构造函数信息
22 ConstructorInfo[] tmpConsInfos = tmpType.GetConstructors();
23 foreach (ConstructorInfo tmpConsInfo in tmpConsInfos)
24 {
25 //为构造函数生成调用的参数集合
26 ParameterInfo[] tmpParamInfos = tmpConsInfo.GetParameters();
27 object[] tmpParams = new object[tmpParamInfos.Length];
28 for (int i = 0; i < tmpParamInfos.Length; i++)
29 {
30 tmpParams[i] = tmpAss.CreateInstance(tmpParamInfos[i].ParameterType.FullName);
31 if (tmpParamInfos[i].ParameterType.FullName == "System.String")
32 {
33 tmpParams[i] = "Clark";
34 }
35 }
36
37 //实例化对象
38 object tmpObj = tmpConsInfo.Invoke(tmpParams);
39 Console.WriteLine(tmpObj);
40
41 //获取所有方法并执行
42 foreach (MethodInfo tmpMethod in tmpType.GetMethods())
43 {
44 //为方法的调用创建参数集合
45 tmpParamInfos = tmpMethod.GetParameters();
46 tmpParams = new object[tmpParamInfos.Length];
47 for (int i = 0; i < tmpParamInfos.Length; i++)
48 {
49 tmpParams[i] = tmpAss.CreateInstance(tmpParamInfos[i].ParameterType.FullName);
50 if (tmpParamInfos[i].ParameterType.FullName == "System.String")
51 {
52 tmpParams[i] = "Clark Zheng";
53 }
54 if (tmpParamInfos[i].ParameterType.FullName == "System.Int32")
55 {
56 tmpParams[i] = 27;
57 }
58 }
59 tmpMethod.Invoke(tmpObj, tmpParams);
60 }
61
62 //调用完方法后再次打印对象,比较结果
63 Console.WriteLine(tmpObj);
64 }
65 }
66
67 Console.ReadLine();
68 }
69 }
70}
结果:
Name: Clark, Age: 0
Name: Clark Zheng, Age: 27
示例下载:http://www.cnblogs.com/Files/reonlyrun/CSharp25QExample07.rar