=================插件实施与应用基本流程

1,开发此程序的人 提供接口(提供DLL)

2,第三方开发团队(开发插件)严格按照接口,实现功能。并打包成DLL

3,使用者下载第三方开发团队开发出来的插件,并把查询复制到程序相应的文件夹里

 

=================程序开发思想

1,在程序中创建一个类库,在内库中定义一个接口

2,第三方开发团队拿到接口,并是实现其功能。打包成dll文件

3,copy第三方团队开发的dll到程序指定的目录

4,找到dll存放的路径

5,遍历所有dll的路径

6,通过路径加载程序集(插件)

7,加载程序集(插件)中所有的公共的类

8,加载接口类

9,遍历插件的所有的公共类

10,判断接口是否能够与插件里的类对接

11,如果能,则反射

 

===================================================Form1主窗体

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Reflection;
namespace MyReflect
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
LoadAssembly();
}
private void LoadAssembly()
{
//获取存放dll插件的文件路径
string mypath = Directory.GetCurrentDirectory() + "\\MyDll";
string[] filepath = Directory.GetFiles(mypath, "*.dll");
//办理路径
foreach (string file in filepath)
{
//根据路径加载文件下的程序集
Assembly ass = Assembly.LoadFrom(file);
//获取程序集中所有公有的类
Type[] tclass= ass.GetExportedTypes();
//获取接口的类
Type tform= typeof(InterfaceForm.FormTitle);
//------------------------------------------------
int i = 0;
//------------------------------------------------
//遍历插件的所有公共类
foreach (Type t in tclass)
{
//判断接口是否能与插件的类对接
if (tform.IsAssignableFrom(t))
{
//反射
InterfaceForm.FormTitle tf = Activator.CreateInstance(t) as InterfaceForm.FormTitle;
Button b = new Button();
b.Text = t.Name;
b.Location = new Point(0, i);
b.Tag = tf;
b.Click += b_Click;
Controls.Add(b);
}
i += 50;
}
}
}
void b_Click(object sender, EventArgs e)
{
Button b= sender as Button;
InterfaceForm.FormTitle tf= b.Tag as InterfaceForm.FormTitle;
tf.GetFT(this);
}
}
}

=============================================接口

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace InterfaceForm
{
public interface FormTitle
{
void GetFT(Form f);
}
}

=============================================插件

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace IsOk
{
public class Class1:InterfaceForm.FormTitle
{
public void GetFT(Form f)
{
f.Text = "我是class1";
}
}
}

 【如果需要源代码,请给我留言】