我有2个dll,一个带接口,另一个实际使用接口。 我可以使用反射来调用第二个dll,但我想知道是否可以使用该界面获取有关它的更多信息。
我有类似......
// the interface dll
namespace Mynamespace{
public interface Interface1
{
int Add( int a, int b);
}
}
和同一个dll中的另一个界面...
请注意,它来自第一个。
namespace Mynamespace{
public interface Interface2 : Interface1
{
int Sub( int a, int b);
}
}
然后我使用反射
调用方法// get the 2 interfaces
var asm = Assembly.LoadFile( dllInterfacePath);
var type1 = asm.GetType("Mynamespace.Interface1");
var type2 = asm.GetType("Mynamespace.Interface2");
// get the main class
var asmDll = Assembly.LoadFile( dllPath);
var type = asmDll.GetType("MyMS.SomeClass");
// create an instance
var instance = Activator.CreateInstance( type, null );
现在我的问题是如何判断创建的实例是从Interface2
还是Interface1
派生出来的,我可以查找方法" Sub(...)"如果它不存在,那么我知道它是Interface1
类型。
但我想知道是否有更好的功能来动态实现这个目标?
我无法使用
typeof(Interface1).IsAssignableFrom(typeof(MyMS.SomeClass));
因为Interface1
和MyMS.SomeClass
都是动态加载的,而且未在项目中引用。
答案 0 :(得分:3)
You don't have to use the typeof
to have a type reference, the reflection API works well for dynamically loaded types, too.
Sorry, but it does not work. typeof(Interface1).IsAssignableFrom(typeof(MyMS.SomeClass)); or type.IsAssignableFrom(type1); does not work
It does work but by calling LoadFile
you are basically loading the same interface assembly twice, thus making it impossible to refer to the same interface type on the class that implements it:
https://blogs.msdn.microsoft.com/suzcook/2003/09/19/loadfile-vs-loadfrom/
Just replace LoadFile
with LoadFrom
or even ReflectionOnlyLoadFrom
:
I just recreated your scenario, I have an assembly with the interface and another assembly with the implementation.
Assembly interfaceLib = Assembly.ReflectionOnlyLoadFrom( "InterfaceLib.dll" );
Assembly implementationLib = Assembly.ReflectionOnlyLoadFrom( "ImplementationLib.dll" );
var i = interfaceLib.GetType( "InterfaceLib.Interface1" );
var t = implementationLib.GetType( "ImplementationLib.Class1" );
var b = i.IsAssignableFrom( t );
Console.WriteLine( b );
// prints "true"
If I switch to LoadFile
I get false
.