Dav*_*fer 20 .net c# generics reflection interface
关于" 通过反射实现接口 "的答案显示了如何获得接口的所有实现.但是,给定通用接口,IInterface<T>以下不起作用:
var types = TypesImplementingInterface(typeof(IInterface<>))
Run Code Online (Sandbox Code Playgroud)
任何人都可以解释我如何修改该方法?
Cod*_*aos 21
你可以使用这样的东西:
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));
}
Run Code Online (Sandbox Code Playgroud)
它可以抛出一个TypeLoadException但是这是原始代码中已经存在的问题.例如在LINQPad中它不起作用,因为某些库无法加载.