[英].NET - Getting all implementations of a generic interface?
An answer on " Implementations of interface through Reflection " shows how to get all implementations of an interface. “ 通过反射实现接口”的答案显示了如何获取接口的所有实现。 However, given a generic interface, IInterface<T>
, the following doesn't work:但是,给定通用接口IInterface<T>
,以下内容不起作用:
var types = TypesImplementingInterface(typeof(IInterface<>))
Can anyone explain how I can modify that method?谁能解释我如何修改该方法?
You can use something like this:你可以使用这样的东西:
public static bool DoesTypeSupportInterface(Type type, Type inter)
{
if(inter.IsAssignableFrom(type))
return true;
if(type.GetInterfaces().Any(i => i.IsGenericType && i.GetGenericTypeDefinition() == inter))
return true;
return false;
}
public static IEnumerable<Type> TypesImplementingInterface(Type desiredType)
{
return AppDomain
.CurrentDomain
.GetAssemblies()
.SelectMany(assembly => assembly.GetTypes())
.Where(type => DoesTypeSupportInterface(type, desiredType));
}
It can throw a TypeLoadException
though but that's a problem already present in the original code.虽然它可以抛出TypeLoadException
但这是原始代码中已经存在的问题。 For example in LINQPad it doesn't work because some libraries can't be loaded.例如在 LINQPad 中它不起作用,因为无法加载某些库。
It doesn't work because IInterface<object>
(using System.Object
for T as an example) doesn't inherit from the "open" generic type IInterface<>
.它不起作用,因为IInterface<object>
(以System.Object
为例)不是从“开放”泛型类型IInterface<>
继承的。 A "closed" generic type is a root type, just like IFoo
. “封闭”泛型类型是根类型,就像IFoo
一样。 You can only search for closed generic types, not open ones, meaning you could find everything that inherits from IInterface<int>
.您只能搜索封闭的泛型类型,而不是开放的泛型类型,这意味着您可以找到从IInterface<int>
继承的所有内容。 IFoo
does not have a base class, nor does IInterface<object>
or IInterface<string>
etc. IFoo
没有基础 class,也没有IInterface<object>
或IInterface<string>
等。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.