反射实例
![](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
1 public class ClassPerson
2 {
3 public ClassPerson()
4 : this(null)
5 {
6 }
7 public ClassPerson(string strname)
8 {
9 name = strname;
10 }
11 private string name = null;
12 private string sex;
13 private int age;
14 public string Name
15 {
16 set { name = value; }
17 get { return name; }
18 }
19 public string Sex
20 {
21 set { sex = value; }
22 get { return sex; }
23 }
24 public int Age
25 {
26 set { age = value; }
27 get { return age; }
28 }
29 public void SayHello()
30 {
31 if (name == null)
32 {
33 System.Console.WriteLine("Hello World");
34 }
35 else
36 {
37 System.Console.WriteLine("Hello," + name);
38 }
39 }
40 }
在新建控制台程序把Recenflence.dll添加到bin文件夹并进行引用
![](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
1 /*Assembly 类是using System.Reflection定义的!允许访问给定程序集的元数据,它包含可以加载
2 和执行程序集的方法
3 */
4 Assembly ass = Assembly.LoadFrom("Recenflence.dll");
5 /*Assembly.LoadFrom与Assembly.Load的主要区别Load()的参数是程序集的名称运行库会在各个位置
6 上搜索该程序集这些位置包括本地目录和全局程序集高速缓存而LoadFrom()的参数是程序集的完整路径名
7 ,不会在其他位置搜索该程序集
8 * */
9 /*
10 System.Type 类 通过这个类可以访问任何给定数据类型的信息
11 */
12 Type classperson = null;
13 Type[] mytypes = ass.GetTypes();//返回一个包含所有类型信息的System.Type引用数组
14 foreach (Type t in mytypes)
15 {
16 Console.WriteLine(t.Name);//返回类名称
17 if (t.Name == "ClassPerson")
18 {
19 classperson = t;
20 }
21 }
22 Console.WriteLine("列出ClassPerson类中的所有方法");
23 MethodInfo[] mif = classperson.GetMethods();//返回类中的所有方法
24 foreach (MethodInfo mf in mif)
25 {
26 Console.WriteLine(mf.Name);//输出类中的所有方法的名称
27 }
28 Console.WriteLine("实例化ClassPerson,并调用SayHello方法");
29 /*
30 *Activator类 用以在本地或从远程创建对象类型,或获取对现有远程对象的引用。
31 */
32 Object objName = Activator.CreateInstance(classperson, "litianping");
33 /*
34 *Activator.CreateInstance 使用与指定参数匹配程度最高的构造函数创建指定类型的实例。
35 *即调用类的有参构造函数
36 * public ClassPerson(string strname)
37 {
38 name = strname;
39 }
40 */
41 Object obj = Activator.CreateInstance(classperson);
42 /*
43 *Activator.CreateInstance 使用与指定参数匹配程度最高的构造函数创建指定类型的实例。
44 *即调用类的无参构造函数
45 * public ClassPerson()
46 : this(null)
47 {
48 * }
49 */
50 MethodInfo msayhello = classperson.GetMethod("SayHello");
51
52 msayhello.Invoke(obj, null);
53 /*
54 * MethodInfo.Invoke调用由此 MethodInfo 实例反射的方法或构造函数。
55 */
56 msayhello.Invoke(objName, null);
57 System.Console.ReadLine();
58 }
![](https://images.cnblogs.com/cnblogs_com/zzandlx/12.jpg)
通过反射把Recenflence.dll中的方法显示并调用Recenflence.dll中的方法