简体   繁体   中英

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. 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

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.

Most likely reason - both DLL and your code have own version of 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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