动态反射

这个节课带来的是反射,有很多人我想他肯定知道有反射但是他们都不会用。包括有1-2年开发经验的人。

前期绑定和后期绑定就是使用的反射。

其实反射就是using System.Reflection里面的 主要使用2个类:第1个类就是Type类 第2个类就是Assembly类。

很多人就会问到Assembly这个类怎么使用。

因为初学者都基本知道Type类怎么使用,Assembly类就不知道怎么使用了。

接下来我们一起来看看代码

我必须1个接口 1个类来继承接口 1个类来实现动态反射,1界面调用

跟它们取了个名字:

接口 : IMessageBox

继承接口类 :MyMessageBox

反射类 : MessageBoxFactory

调用类 :Test->WinForm2

以上里面只有一个方法我毕竟是演示与讲解,希望大家自己下去多多练习

 

1:接口

 1  using  System;
 2  using  System.Collections.Generic;
 3  using  System.Text;
 4 
 5  namespace  MyTest.TestLib
 6  {
 7       public   interface  IMessageBox
 8      {
 9           string  Show();
10      }
11  }
12 

 

2:继承接口类

 

ExpandedBlockStart.gif 代码
 1  using  System;
 2  using  System.Collections.Generic;
 3  using  System.Linq;
 4  using  System.Text;
 5 
 6  namespace  MyTest.TestLib
 7  {
 8       public   class  MyMessageBox : IMessageBox
 9      {
10           #region  IMessageBox 成员
11           // 继承接口返回一个String,接口就不讲了。上一章讲过了
12           public   string  Show()
13          {
14               return   " Hello Word " ;
15          }
16 
17           #endregion
18      }
19  }
20 

 

 

3:反射(抽象工厂)

 1  using  System;
 2  using  System.Collections.Generic;
 3  using  System.Linq;
 4  using  System.Text;
 5  using  System.Reflection;
 6 
 7  namespace  MyTest.TestLib
 8  {
 9       public   class  MessageBoxFactory
10      {
11           // 动态反射
12           public   static  IMessageBox MyMessageBoxFactory()
13          {
14               // 一定要写清楚程序集(namespace)
15               string  path  =   " MyTest.TestLib " ; // 指定程序集
16               return  (IMessageBox)Assembly.Load(path).CreateInstance(path  +   " .MyMessageBox " ); // 指定程序集合->下面的类
17          }
18      }
19  }
20 

 

界面调用类 WinForm2

 

ExpandedBlockStart.gif
 1  using  System;
 2  using  System.Collections.Generic;
 3  using  System.ComponentModel;
 4  using  System.Data;
 5  using  System.Drawing;
 6  using  System.Linq;
 7  using  System.Text;
 8  using  System.Windows.Forms;
 9  using  MyTest.TestLib;
10  namespace  Test
11  {
12       public   partial   class  Form2 : Form
13      {
14           public  Form2()
15          {
16              InitializeComponent();
17          }
18 
19           private   void  button1_Click( object  sender, EventArgs e)
20          {
21              IMessageBox IMyMessageBox  =  MessageBoxFactory.MyMessageBoxFactory();
22              MessageBox.Show(IMyMessageBox.Show());
23          }
24      }
25  }
26 

 

 

转载于:https://www.cnblogs.com/XiaoLongZhang/archive/2010/02/03/1662605.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值