在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放置在指定的插件目錄中即可。