【发布时间】:2016-08-15 17:18:24
【问题描述】:
我有 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 都是动态加载的,不会在项目中引用。
【问题讨论】:
-
@wiktor-zychla,我已经对其进行了编辑以澄清为什么这不是重复的。
-
您不必使用
typeof来获得类型引用。该 api 也适用于动态加载的类型。 -
对不起,它不起作用。
typeof(Interface1).IsAssignableFrom(typeof(MyMS.SomeClass));或type.IsAssignableFrom(type1);不起作用 -
确实有效,看看我的详细回答。
-
你不能直接说:
type1.IsAssignableFrom(type)吗?
标签: c# .net reflection