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

时间:2013-10-07 18:27:03

标签: c# .net dll interface

我有一个类我试图通过使用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和使用接口时,我是一个巨大的新手。

2 个答案:

答案 0 :(得分:3)

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

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

答案 1 :(得分:0)

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