/// <summary> /// 接口中首先定义方法名称 /// </summary> public interface IPlugs { string Name { get; } string Process(string str); }
/// <summary> /// 实现接口方法 /// </summary> class ToLower:IPlgus.IPlugs { public string Name { get { return "大写转小写"; } } public string Process(string str) { return str.ToLower(); } }
然后生成DLL文件复制到主程序bin文件夹中
using System.Reflection; /// <summary> /// 动态获取dll并且添加到主程序 /// </summary> public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { Type t=typeof(IPlgus.IPlugs); //获取接口type string path = AppDomain.CurrentDomain.BaseDirectory; //获取程序执行根目录 path += "IPlugs\"; string[] strs = System.IO.Directory.GetFiles(path, "*.dll"); //获取对应目录中dll的文件路径 if(strs.Length>0) { for (int i = 0; i < strs.Length; i++) { Assembly ass = Assembly.LoadFile(strs[i]); //获取程序集 if(ass!=null) { Type[] types = ass.GetTypes(); //获取程序集中的Type if(types.Length>0) { foreach (Type item in types) { if(t.IsAssignableFrom(item)) { ToolStripMenuItem tool = new ToolStripMenuItem(); PropertyInfo pinfo = item.GetProperty("Name"); //获取Type中的属性 object obj = Activator.CreateInstance(item); //根据获取的Type实例化对象 object value = pinfo.GetValue(obj); //获取Type属性中的值 tool.Text = value.ToString(); // tool.Click += tool_Click; tool.Click += new EventHandler(tool_Click); tool.Tag = item; this.功能ToolStripMenuItem.DropDownItems.Add(tool); } } } } } } } void tool_Click(object sender, EventArgs e) { string text = this.textBox1.Text.Trim(); if(text=="") { MessageBox.Show("没法转"); } ToolStripMenuItem tool=sender as ToolStripMenuItem; Type t=(Type)tool.Tag; object model = Activator.CreateInstance(t); MethodInfo minfo=t.GetMethod("Process"); //获取Type中的方法 object newtext = minfo.Invoke(model, new object[] { text }); //执行从Type中获取的方法 this.textBox1.Text = newtext.ToString(); } }