在C#中,要实现插件化架构,可以使用接口和属性来定义插件的行为和数据。以下是一个简单的示例:
IPlugin
的接口:public interface IPlugin
{
string Name { get; }
string Description { get; }
void Execute();
}
System.Reflection
命名空间中的类来动态加载插件:using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
public class PluginManager
{
private List<IPlugin> _plugins;
public PluginManager()
{
_plugins = new List<IPlugin>();
}
public void LoadPlugins(string path)
{
if (!Directory.Exists(path))
return;
string[] files = Directory.GetFiles(path, "*.dll");
foreach (string file in files)
{
Assembly assembly = Assembly.LoadFile(file);
Type[] types = assembly.GetTypes();
foreach (Type type in types)
{
if (type.IsClass && !type.IsAbstract && typeof(IPlugin).IsAssignableFrom(type))
{
IPlugin plugin = Activator.CreateInstance(type) as IPlugin;
_plugins.Add(plugin);
}
}
}
}
public List<IPlugin> GetPlugins()
{
return _plugins;
}
}
IPlugin
接口:public class MyPlugin : IPlugin
{
public string Name => "My Plugin";
public string Description => "This is a sample plugin.";
public void Execute()
{
Console.WriteLine("Hello from MyPlugin!");
}
}
PluginManager
加载和管理插件:class Program
{
static void Main(string[] args)
{
PluginManager pluginManager = new PluginManager();
pluginManager.LoadPlugins("plugins");
List<IPlugin> plugins = pluginManager.GetPlugins();
foreach (IPlugin plugin in plugins)
{
Console.WriteLine($"Name: {plugin.Name}");
Console.WriteLine($"Description: {plugin.Description}");
plugin.Execute();
Console.WriteLine();
}
}
}
这样,你就可以根据需要创建和添加新的插件,而不需要修改主程序代码。只需确保插件实现了IPlugin
接口,并将插件DLL放置在指定的插件目录中即可。