问题描述
|
关于“通过反射实现接口”的答案显示了如何获取接口的所有实现。但是,给定通用接口
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));
}
它可以抛出3英镑,但这是原始代码中已经存在的问题。例如,在LINQPad中,由于某些库无法加载,因此无法使用。
,这是行不通的,因为ѭ4T(以T为例,以from5ѭ为例)不会从\“ open \”泛型类型IInterface<>
继承。 \“ closed \”泛型类型是根类型,就像IFoo
。您只能搜索封闭的泛型类型,而不能搜索开放的泛型类型,这意味着您可以找到继承自IInterface<int>
的所有内容。 IFoo
没有基类,IInterface<object>
或IInterface<string>
等也没有。