
# 插件
概念:插件(又译外挂,英文为Plug-in、Plugin、add-in、addin、add-on、addon或extension)是一种电脑程序,透过和应用程序(例如网页浏览器,电子邮件客户端)的互动,用来替应用程序增加一些所需要的特定的功能。最常见的有游戏、网页浏览器的插件和媒体播放器的插件。
# 通过C#实现插件式开发
为了项目更好的扩展,下面通过实战了解以下动态加载技术
# 开发步骤
- 1、新建一个类库项目,定义接口
```C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PluginInterface1
{
public interface IPlugin
{
string Show();
}
}
```
- 2、编写一个类库项目,实现该接口
注意点,这里要引用第一个项目的dll类库,找到源头接口
```C#
using PluginInterface1;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ClassLibrary
{
public class PluginClass : IPlugin
{
public string Show()
{
return "我就是插件,我就是外挂";
}
}
}
```
- 3、主程序利用反射机制找到两个类库,并实现该方法
新建一个控制台应用程序项目。新建一个文件夹"Plugins"放入两个类库编译完的dll,方便主程序调用
实现代码如下:
```C#
using PluginInterface1;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace MyConsoleApp
{
internal class Program
{
static void Main(string[] args)
{
Program p = new Program();
List<string> pluginpath = p.FindPlugin();
pluginpath = p.DeleteInvalidPlungin(pluginpath);
foreach (string filename in pluginpath)
{
try
{
//获取文件名
string asmfile = filename;
string asmname = Path.GetFileNameWithoutExtension(asmfile);
if (asmname != string.Empty)
{
// 利用反射,构造DLL文件的实例
Assembly asm = Assembly.LoadFile(asmfile);
//利用反射,从程序集(DLL)中,提取类,并把此类实例化
Type[] t = asm.GetExportedTypes();
foreach (Type type in t)
{
if (type.GetInterface("IPlugin") != null)
{
IPlugin show = (IPlugin)Activator.CreateInstance(type);
Console.Write(show.Show());
}
}
}
}
catch (Exception ex)
{
Console.Write(ex.Message);
}
}
Console.ReadLine();
}
private List<string> FindPlugin()
{
List<string> pluginpath = new List<string>();
try
{
//获取程序的基目录
string path = "C:\\Users\\Think\\source\\repos\\PluginInterface\\MyConsoleApp";
//合并路径,指向插件所在目录。
path = Path.Combine(path, "Plugins");
foreach (string filename in Directory.GetFiles(path, "*.dll"))
{
pluginpath.Add(filename);
}
}
catch (Exception ex)
{
Console.Write(ex.Message);
}
return pluginpath;
}
//载入插件,在Assembly中查找类型
private object LoadObject(Assembly asm, string className, string in