【问题标题】:Get derived class via dynamic Assembly loading?通过动态程序集加载获取派生类?
【发布时间】: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));

因为Interface1MyMS.SomeClass 都是动态加载的,不会在项目中引用。

【问题讨论】:

  • @wiktor-zychla,我已经对其进行了编辑以澄清为什么这不是重复的。
  • 您不必使用typeof 来获得类型引用。该 api 也适用于动态加载的类型。
  • 对不起,它不起作用。 typeof(Interface1).IsAssignableFrom(typeof(MyMS.SomeClass));type.IsAssignableFrom(type1); 不起作用
  • 确实有效,看看我的详细回答。
  • 你不能直接说:type1.IsAssignableFrom(type) 吗?

标签: c# .net reflection


【解决方案1】:

您不必使用typeof 来获得类型引用,反射 API 也适用于动态加载的类型。

对不起,它不起作用。 typeof(Interface1).IsAssignableFrom(typeof(MyMS.SomeClass));或 type.IsAssignableFrom(type1);不工作

它确实有效,但是通过调用LoadFile,您基本上是两次加载相同的接口程序集,因此无法在实现它的类上引用相同的接口类型:

https://blogs.msdn.microsoft.com/suzcook/2003/09/19/loadfile-vs-loadfrom/

只需将LoadFile 替换为LoadFrom 甚至ReflectionOnlyLoadFrom

我刚刚重新创建了您的场景,我有一个带有接口的程序集和另一个带有实现的程序集。

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"

如果我切换到LoadFile,我会得到false

【讨论】:

  • LoadFileLoadFrom 是个问题,如果你不去寻找,两者之间的细微差别(但很重要)并不是很明显。
猜你喜欢
  • 2012-01-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多