C#_Assembly-Reflection_程序集与反射 练习<二> 记事本插件编写

//续上  上篇我们编写了在格式中动态加载dll文件  获取其中的类型  然后找到我们定义的接口类型

为该接口类型赋值  然后将对象保存在 ToolMenuStripItem 的Tag中   为该item单击事件注册函数

将tag中的对象传递过去   实现接口中定义的方法   (其实就实现了将文本转为大写。。)

Today,We'll...  好了,今天我们接着做   首先 我们打开之前的工程    为其添加 和转换大写 一样的 转换小写 :)

首先,我们要明确 转换小写 转换大写  所用的接口定义是一样的,这里我们先回顾下之前定义的接口类型:

//------------------------定义插件的接口规范-------------

 1 namespace MyNotepadInterface
 2 {
 3     public interface IEditor
 4     {
 5         //定义一个只读属性   表示插件的名称
 6          string PluginName
 7         {
 8             get;
 9         }
10 
11         //运行该插件的方法
12         void Run(TextBox txtBox);
13     }
14 
15 }

我们可以看出其(IEditor)有 只读属性 PluginName  以及 Run方法 ,也就是说 我们无论今后写多少个插件,插件的名称  我们就用PluginName

来保存,调用Run方法来执行 该插件 

//----------------------转换小写---------------------

新建类库  定义实现IEditor类型:

jiangzi:

  同样记得引用该接口类型哈

定义ToLower类型:

 1 namespace MyDll.ToLower
 2 {
 3     public class ToLower : IEditor
 4     {
 5         public string PluginName
 6         {
 7             get { return "转成小写"; }
 8         }
 9 
10         public void Run(System.Windows.Forms.TextBox txtBox)
11         {
12             txtBox.Text = txtBox.Text.ToLower();
13         }
14     }
15 }

和ToUpper一样  ~  接下来要做的就是 清理  重新生成该类库   找到dl文件 复制到Plugins文件夹下

下面我们来添加改变文本字体的插件   :

首先 我们添加类库  定义其实现IEditor的类型:

在修改字体中我们需要弹出 修改字体的对话框  这个对话框我们就做在 该类库中

 1 namespace MyDll.ChangeFont
 2 {
 3     public class ChangeFont:MyNotepadInterface.IEditor
 4     {
 5 
 6         public string PluginName
 7         {
 8             get { return "修改字体"; }
 9         }
10 
11         public void Run(System.Windows.Forms.TextBox txtBox)
12         {
13             changeFontForm cff = new changeFontForm(txtBox);
14             cff.Show();
15         }
16     }
17 }

这里定义的changFontForm就是要弹出的修改字体的窗体:

因为这里的构造函数 

new changeFontForm(txtBox)   传递了TextBox类型   所以在changeFontForm需要定义该构造函数

 1   public partial class changeFontForm : Form
 2     {
 3         private TextBox txtBox;
 4 
 5         public changeFontForm()
 6         {
 7             InitializeComponent();
 8         }
 9 
10         public changeFontForm(TextBox txtBox)      //定义有参数的构造函数
11             :this()
12         {
13             // TODO: Complete member initialization
14             this.txtBox = txtBox;              //将通过实现接口类型的子对象 ( public class ChangeFont:MyNotepadInterface.IEditor) 中传递的参数 保存
15         }
16 
17         private void button1_Click(object sender, EventArgs e)
18         {
19             this.txtBox.Font = new Font(comboBox1.Text, float.Parse(comboBox2.Text));
20             this.Close();
21         }
22 
23     }

好了  清理重新生成  移动dll文件位置 至 Plugins文件夹下:

噢了~

 

posted on 2015-12-02 09:51  许清池  阅读(195)  评论(0编辑  收藏  举报

导航