.NET - 获得一个通用接口的所有实现? [英] .NET - Getting all implementations of a generic interface?

查看:288
本文介绍了.NET - 获得一个通用接口的所有实现?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在<一的回答href="http://stackoverflow.com/questions/80247/implementations-of-interface-through-reflection">Implementations通过反射界面的说明如何获取一个接口的所有实现。然而,鉴于通用接口, IInterface&LT; T&GT; ,下面不工作:

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));

}

它可以尽管抛出一个TypeLoader异常,但是这是一个问题已经美元的原来的$ C $中c p $ psent。例如,在linqpad这是行不通的,因为无法加载一些库。

It can throw a TypeLoader exception 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆