C#插件入门
(一)建立接口类库IDialog,添加接口文件IShowDialog.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace IDialog { public interface IShowDialog { void ShowMyDialog(); } }
(二)新建插件,添加类库Dialog,实现接口IDalog类Dialog,添加IDialog接口类库的引用就不必多说了
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows.Forms; using IDialog; namespace Dialog { public class Dialog:Form,IShowDialog { public void ShowMyDialog() { Form frmMyForm = new Form(); frmMyForm.Text = "Hello World"; frmMyForm.Show(); } } }
(三)建立Form应用程序,装载插件Dialog,并显示插件,添加ListBox用来显示插件的名字,
两个Button控件,btnLoadPlugs用来装载插件,btnRunPlugs用来运行插件
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Collections; using System.Reflection; using System.IO; namespace MainInvokePlugins { public partial class frmMain : Form { public frmMain() { InitializeComponent(); } private ArrayList listPlugs = new ArrayList();
private void btnLoadPlugs_Click(object sender, EventArgs e) { string []files= Directory.GetFiles(Application.StartupPath); try { foreach (string item in files) { if (item.ToUpper().EndsWith(".DLL")) { Assembly a = Assembly.LoadFile(item); Type[] ts = a.GetTypes(); foreach (Type t in ts) { if (t.GetInterface("IShowDialog") != null) { listPlugs.Add(a.CreateInstance(t.FullName)); this.listNames.Items.Add(a.FullName); ; } } } } } catch (Exception ex) { MessageBox.Show(ex.Message); } } private void btnRunPlugs_Click(object sender, EventArgs e) { if (this.listNames.SelectedIndex==-1) { return; } else { try { object plug = this.listPlugs[this.listNames.SelectedIndex]; Type t = plug.GetType(); MethodInfo showDialog = t.GetMethod("ShowMyDialog"); showDialog.Invoke(plug, null); } catch (Exception ex) { MessageBox.Show(ex.Message); } } } } }