.NET - 获取通用接口的所有实现? [英] .NET - Getting all implementations of a generic interface?
本文介绍了.NET - 获取通用接口的所有实现?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
关于通过反射实现接口"的答案展示了如何获得所有接口的实现.但是,给定一个通用接口 IInterface
,以下内容不起作用:
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:
var types = TypesImplementingInterface(typeof(IInterface<>))
谁能解释我如何修改该方法?
Can anyone explain how I can modify that method?
推荐答案
你可以这样使用:
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 中它不起作用,因为某些库无法加载.
It can throw a TypeLoadException
though but that's a problem already present in the original code. For example in LINQPad it doesn't work because some libraries can't be loaded.
这篇关于.NET - 获取通用接口的所有实现?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文