我正在尝试在 C# 中实现一个插件系统,为此我创建了以下类和接口:
包含在加载器和插件中:
interface IDevicePlugin {
string GetName();
string GetVersion();
}
插件代码(编译为 .dll)
public class DummyPlugin : IDevicePlugin {
protected string name;
protected string version;
public string GetName() {
return name;
}
public string GetVersion() {
return version;
}
}
加载插件的代码如下:
IDevicePlugin thePlugin;
Assembly plugin = Assembly.LoadFrom("plugin.dll");
foreach (Type pluginType in plugin.GetTypes()) {
if (pluginType.IsPublic && !pluginType.IsAbstract) {
Type typeInterface = pluginType.GetInterface("IDevicePlugin", true);
if (typeInterface != null) {
// the plugin implements our IDevicePlugin interface
thePlugin = (IDevicePlugin)Activator.
CreateInstance(plugin.GetType(pluginType.ToString()));
}
}
}
这会崩溃:
Unable to cast object of type 'PluginTest.DummyPlugin' to type 'PluginTest.IDevicePlugin'.