在C#中,要實現動態加載,可以使用反射和動態編譯的方法。這里給出一個簡單的示例,展示如何使用動態編譯的方法來實現插件的動態加載。
public interface IPlugin
{
string Name { get; }
void Execute();
}
public class PluginLibrary
{
private Dictionary<string, Assembly> _assemblies = new Dictionary<string, Assembly>();
public void AddAssembly(string assemblyName, Assembly assembly)
{
_assemblies[assemblyName] = assembly;
}
public IPlugin GetPlugin(string assemblyName, string className)
{
if (_assemblies.TryGetValue(assemblyName, out Assembly assembly))
{
Type type = assembly.GetType(className);
if (type != null && typeof(IPlugin).IsAssignableFrom(type))
{
return (IPlugin)Activator.CreateInstance(type);
}
}
return null;
}
}
public class PluginA : IPlugin
{
public string Name => "PluginA";
public void Execute()
{
Console.WriteLine("PluginA executed.");
}
}
public class Program
{
public static void Main(string[] args)
{
PluginLibrary pluginLibrary = new PluginLibrary();
// 加載插件程序集
Assembly assembly = Assembly.LoadFrom("PluginA.dll");
pluginLibrary.AddAssembly("PluginA", assembly);
// 獲取并執行插件
IPlugin plugin = pluginLibrary.GetPlugin("PluginA", "PluginA");
if (plugin != null)
{
plugin.Execute();
}
else
{
Console.WriteLine("Plugin not found.");
}
}
}
注意:這個示例中的插件是靜態加載的,為了實現動態加載,你需要將插件程序集存儲在一個外部文件中(如DLL文件),然后在運行時動態加載它們。這可能需要使用文件I/O和反射來完成。