本文介绍了接口和后期在C#绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我以前在C#中的插件系统工作正常,这就是为什么我很困惑,为什么这个新的,独立的插件系统不工作我所期望的方式做到了这一点。

I've done this before in C# for a plugin system which works fine, which is why I'm puzzled as to why this new, separate plugin system is not working the way I would expect.

我有我的插件组件 - 姑且称之为plugin.dll,我有我的主要部件 - 姑且称之为APP.EXE。

I have my plugin assembly - let's call it "plugin.dll" and I have my main assembly - let's call it App.exe.

我有 IMyObject 称为一个接口及其实现,为MyObject 无一不是在plugin.dll定义。我复制了确切的code文件 IMyObject (该插件开发人员提供给我)到我APP.EXE主要部件。

I have an interface called IMyObject and its implementation, MyObject and both are defined in plugin.dll. I've copied the exact code file for IMyObject (which the plugin developer has provided to me) into my main App.exe assembly.

我得到一个 InvalidCastException的当我尝试我加载使用反射对象映射到该对象实现的接口。我的知道的对象实现它,因为

I get an InvalidCastException when I try to cast the object I load using reflection to the interface that the object implements. I know the object implements it because

t.GetInterface(typeof运算(IMyObject).FullName)!= NULL

是真实的。我还可以浏览为MyObject 在Visual Studio中的对象资源管理器,我可以看到它实现 IMyObject

is true. I can also browse MyObject in the object explorer in Visual Studio and I can see that it implements IMyObject.

下面就是它出了问题:

 if (ifaceType != null)
 {
    ConstructorInfo constructor = ifaceType.GetConstructor(new Type[] { });

    if (constructor != null)
    {

       object obj = constructor.Invoke(null); // this works - obj is assigned an
                                              // instance of MyObject

       IMyObject myObj = (IMyObject)obj;      // triggers InvalidCastException
    }
 }

这是我能我在做什么了,我这个之前实施的方式之间看到的唯一区别是,接口是两个独立的组件定义(即使code文件是相同的,它们属于相同的命名空间)。

The only difference that I can see between what I'm doing now and the way I implemented this before is that the interface is defined in two separate assemblies (even though the code files are identical and they belong to the same namespace).

这是我的麻烦的原因是什么?如果是这样,我怎么能连接到我的插件不链接在编译的时候,并使用在插件本身?

Is this the reason for my trouble? If so, how can I connect to my plugin without linking at compile time, and use an interface that is defined in the plugin itself?

我要补充的是,除了界面,我没有访问源$ C ​​$ C的插件。

I should add that aside from the interface, I do not have access to the source code for the plugin.

推荐答案

尽管这些接口具有相同的code,它们是两个不同的组件两个独立接口(你可以打印他们AssemblyQualifiedNames,看到了差距)。

Even though those interfaces have the same code, they are two separate interfaces in two different assemblies (you could print their AssemblyQualifiedNames and see the difference).

这篇关于接口和后期在C#绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 23:15