[转帖]反射
C#反射Reflection学习随笔(AX)_续2006-11-03 10:01④动态创建对象实例【经典】
是实现抽象工厂的基础,也是实现抽象工厂的核心技术,通过它,可以动态创建一个你想要的对象.如下面的例子是演示如何动态创建ChineseName或EnglishName的实例
1using System;
2using System.Reflection;
3namespace TestReflection
4{
5 class AXzhz_sReflectionExample
6 {
7 public static void Main()
8 {
9 IName name=AbstractFactory.GetName();
10 name.ShowName();
11 }
12 }
13
14 public class AbstractFactory
15 {
16 public static IName GetName()
17 {
18 //s的值以后从Web.config动态获取
19 //把s赋值为:TestReflection.EnglishName,将显示英文名
20 string s = "TestReflection.ChineseName";
21 IName name = (IName)Assembly.Load("TestReflection").CreateInstance(s);
22 return name;
23 }
24 }
25
26 //声明一个接口,它有一个显示"名字"的功能
27 public interface IName
28 {
29 void ShowName();
30 }
31
32 //实现接口,显示中国名字
33 public class ChineseName : IName
34 {
35 public void ShowName()
36 {
37 Console.WriteLine("我叫AX!");
38 Console.ReadLine();
39 }
40 }
41
42 //实现接口,显示英国名字
43 public class EnglishName:IName
44 {
45 void IName.ShowName()
46 {
47 Console.WriteLine("My name is AXzhz!");
48 Console.ReadLine();
49 }
50 }
51}
⑤获得整个解决方案的所有Assembly(这个有点用)
如果你不太清楚自己的解决方案中都用到了哪些Assembly,可以使用下面的方法,如果再想得到Assembly里的信息,见③
1using System;
2using System.Reflection;
3
4namespace TestReflection
5{
6 class ShowAllAssembly
7 {
8 public static void Main()
9 {
10 //获得解决方案的所有Assembly
11 Assembly[] AX = AppDomain.CurrentDomain.GetAssemblies();
12 //遍历显示每个Assembly的名字
13 foreach (object var in AX)
14 {
15 Console.WriteLine("Assembly的名字:"+var.ToString());
16 }
17 //使用一个已知的Assembly名称,来创建一个Assembly
18 //通过CodeBase属性显示最初指定的程序集的位置
19 Console.WriteLine("最初指定的程序集TestReflection的位置:" + Assembly.Load("TestReflection").CodeBase);
20 Console.ReadLine();
21 }
22 }
23}
24 来自http://hi.baidu.com/webprince/blog/item/8a02a5af5f1ee5cc7cd92a9c.html
推荐到鲜果: 查阅更多相关主题的帖子: 反射


评论