2

我正在尝试在 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'.
4

1 回答 1

8

该接口存在两次:
一次在您的 plugin.dll 中,一次在您的加载程序中。
原因是您添加了对包含插件项目接口定义的 *.cs 文件的引用(=链接)。此外,相同的 *.cs 文件是加载程序项目的一部分。
因此,接口被编译到两个程序集中。这是两个不同的接口,即使它们的名称相同!

要解决此问题,您应该执行以下操作:

将加载程序项目的引用添加到插件项目
- 或者 -
为接口创建一个新项目并从加载程序和插件项目中引用此项目。

于 2012-08-31T12:46:46.283 回答