![](/img/trans.png)
[英]Getting and/or ejecting all implementations of a generic interface using structuremap
[英].NET - Getting all implementations of a generic interface?
“ 通过反射实现接口”的答案显示了如何获取接口的所有实现。 但是,给定通用接口IInterface<T>
,以下内容不起作用:
var types = TypesImplementingInterface(typeof(IInterface<>))
谁能解释我如何修改该方法?
你可以使用这样的东西:
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));
}
虽然它可以抛出TypeLoadException
但这是原始代码中已经存在的问题。 例如在 LINQPad 中它不起作用,因为无法加载某些库。
它不起作用,因为IInterface<object>
(以System.Object
为例)不是从“开放”泛型类型IInterface<>
继承的。 “封闭”泛型类型是根类型,就像IFoo
一样。 您只能搜索封闭的泛型类型,而不是开放的泛型类型,这意味着您可以找到从IInterface<int>
继承的所有内容。 IFoo
没有基础 class,也没有IInterface<object>
或IInterface<string>
等。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.