【问题标题】:Class instantiated from DLL does not seem to be implementing interface properly从 DLL 实例化的类似乎没有正确实现接口
【发布时间】:2013-10-07 18:27:02
【问题描述】:

我有一个我试图通过使用 Assembly 和 Activator 实例化的类,这个类实现了一个接口,但是当我通过一个检查类是否实现它的条件来运行该类的实例时,我得到了错误.可能是什么问题?

我正在检查实现的代码:

     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
     }

MyClass 类的代码在所有这些范围之外,在 MyDLL 中

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

我不知道为什么这没有通过条件。我可以实例化类错误吗?另外需要注意的是,在使用 Assembly/Activator 和使用接口方面,我是个大菜鸟。

【问题讨论】:

  • 您正在检查您的实例不是您的接口吗?
  • 很抱歉这看起来很模糊。我在帖子中添加了额外的代码。
  • 你把那个字符串字面量谋杀得很厉害。它是@"C:\MyDLL""C:\\MyDLL"

标签: c# .net dll interface


【解决方案1】:

最可能的原因 - DLL 和您的代码都有自己的 MyInterface 版本。这可能是因为

  • 不想花时间为界面想出好的唯一名称,
  • 有人决定将接口共享为源而不是通过程序集引用,
  • 不同命名空间中的良好命名接口,而您using 是错误的。

【讨论】:

  • 这很有帮助,结果证明是原因!非常感谢你! :)
【解决方案2】:

您可能会直接引用您的程序集。如果是这样,您动态加载的类型将具有相同的名称和命名空间,但运行时会认为它们不同。

【讨论】:

    猜你喜欢
    • 2019-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-04
    • 1970-01-01
    • 2014-01-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多