目标:开发一款支持插件的应用程序。
1.定义插件的基本框架,以后为该应用程序开发的插件都继承该框架。
项目:PluginFramework.dll
//IPlugin.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace PluginFramework
{
public interface IPlugin
{
void Load();
}
}
2.插件开发
项目:MyPlugin.dll
添加引用:PluginFramework.dll
//MyPlugin.cs
using System;
using System.Collections.Generic;
using System.Text;
using PluginFramework;
namespace MyPlugin
{
public class MyPlugin : IPlugin
{
public void Load()
{
Console.WriteLine("Loading MyPlugin...");
}
}
}
3.在应用程序中加载插件
项目:MyApplication.exe
添加引用:PluginFramework.dll
//Program.cs
using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using PluginFramework;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
Assembly assem = Assembly.LoadFrom("FirstPlugin.dll");
Type[] types = assem.GetTypes();
foreach (Type type in types)
{
if (type.GetInterface("IPlugin") != null)
{
((IPlugin)Activator.CreateInstance(type)).Load();
}
}
Console.ReadLine();
}
}
}