反射工厂

ContractedBlock.gif ExpandedBlockStart.gif Code
 1 namespace ReflectionFactoryTest
 2 {
 3    public interface IFruit
 4     {
 5        void Product();
 6     }
 7 
 8 
 9 
10 public class Apples:IFruit
11     {
12         #region IFruit 成员
13 
14         public void Product()
15         {
16             Console.WriteLine("Apples");
17         }
18 
19         #endregion
20     }
21 
22 
23 
24 public class Banana:IFruit
25     {
26 
27         #region IFruit 成员
28 
29         public void Product()
30         {
31             Console.WriteLine("Banana");
32         }
33 
34         #endregion
35     }
36 
37 
38 
39 /// <summary>
40     /// 反射工厂
41     /// 反射工厂的好处是,无论我们再添加几个类,都不用修改这个工厂的方法
42     /// </summary>
43     public class ReflectionFactoryTest
44     {
45         /// <summary>
46         /// 工厂的方法
47         /// </summary>
48         /// <param name="className"></param>
49         /// <returns></returns>
50         public static  IFruit CreateFruit(string className)
51         {
52             //加载程序集,Load()方法的参数是命名空间名,要注意大小写
53             Assembly assembly = Assembly.Load("ReflectionFactoryTest");
54             //通过调用CreateInstance()来生成反射的实例,参数为命名空间名.类名,返回值是object,要强制转换成相应的接口类型
55             IFruit ifruit = assembly.CreateInstance(string.Format("ReflectionFactoryTest.{0}",className)) as IFruit;
56             return ifruit;
57         }
58 
59         
60     }
61 
62 
63 
64  public class Program
65     {
66         static void Main(string[] args)
67         {
68            
69             IFruit ifruit = ReflectionFactoryTest.CreateFruit("Apples");
70            ifruit.Product();
71 
72         }
73     }
74 }
75 

转载于:https://www.cnblogs.com/chenbg2001/archive/2009/11/16/1604077.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值