简体   繁体   English

从DLL实例化的类似乎未正确实现接口

[英]Class instantiated from DLL does not seem to be implementing interface properly

I have a class I am attempting to instantiate through the use of Assembly and Activator, this class implements an interface, however when I run the instance of the class through a conditional that checks that the class implements it, I am getting false. 我有一个试图通过使用Assembly和Activator实例化的类,该类实现了一个接口,但是当我通过检查该类是否实现了该条件的条件来运行该类的实例时,我得到了错误。 What could be the problem? 可能是什么问题呢?

My code where I am checking for implementation: 我正在检查实现的代码:

     string className = MyClass;
     Type type = null;
     Assembly assembly = Assembly.LoadFile("@C:\\MyDLL", new Evidence(AppDomain.CurrentDomain.Evidence));
     type = assembly.GetType(className);
     object instance = Activator.CreateInstance(type);

     //never makes it past this conditional
     if (!(instance is MyInterface)
     {
     //It always endsup in here, when it shouldn't.
     System.Writeline("ERROR");
     }
     else{
     //This is what needs to happen
     }

Code for the class MyClass that is outside the scope of all of this, and in MyDLL MyClass类的代码超出了所有这些范围,并且不在MyDLL中

public class MyClass: MyInterface
{
//Contents irrelevent to my problem
}

I am at a loss as to why this is not passing the conditional. 我不知道为什么这没有通过条件。 Could I be instantiation the class wrong? 我可以实例化该类错误吗? Also to note I am a huge rookie when it comes to using Assembly/Activator and using interfaces. 还需要注意的是,在使用Assembly / Activator和使用接口方面,我是一个非常新手。

Most likely reason - both DLL and your code have own version of MyInterface . 最可能的原因-DLL和您的代码都有自己的MyInterface版本。 This could happen either because 这可能是因为

  • one did not want to spend time to come up with good unique name for interface, 一个人不想花时间为界面想出一个很好的唯一名称,
  • someone decided to share interface as source instead of via assembly reference, 有人决定共享接口作为源,而不是通过程序集引用,
  • good named interfaces in the different namespaces and you are using the wrong one. 在不同名称空间中using良好的命名接口,而您using是错误的接口。

You may be referencing your assembly directly. 您可能直接引用了程序集。 If so, the types you load dynamically will have the identical name and namespace, but are considered different by the runtime. 如果是这样,则动态加载的类型将具有相同的名称和名称空间,但运行时会认为它们是不同的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM