. net -获得通用接口的所有实现
本文关键字:实现 接口 net | 更新日期: 2023-09-27 17:54:18
关于"通过反射实现接口"的回答显示了如何获得一个接口的所有实现。然而,给定一个通用接口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
为T为例)不从"开放"泛型IInterface<>
继承。"封闭"泛型类型是根类型,就像IFoo
一样。您只能搜索封闭泛型,而不能搜索开放泛型,这意味着您可以找到从IInterface<int>
继承的所有类型。IFoo
没有基类,IInterface<object>
和IInterface<string>
等也没有。