通过反射接口的实现 [英] Implementations of interface through Reflection

查看:201
本文介绍了通过反射接口的实现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我怎样才能得到一个接口的所有实现通过反射在C#?

How can I get all implementations of an interface through reflection in C#?

推荐答案

答案是这样的;它会在整个应用领域 - 即每装配目前您的应用程序加载

The answer is this; it searches through the entire application domain -- that is, every assembly currently loaded by your application.

/// <summary>
/// Returns all types in the current AppDomain implementing the interface or inheriting the type. 
/// </summary>
public static IEnumerable<Type> TypesImplementingInterface(Type desiredType)
{
    return AppDomain
           .CurrentDomain
           .GetAssemblies()
           .SelectMany(assembly => assembly.GetTypes())
           .Where(type => desiredType.IsAssignableFrom(type));
}

据这样使用;

var disposableTypes =  TypesImplementingInterface(typeof(IDisposable));

您可能还需要此功能来找到实际的具体类型 - 即,过滤出的摘要,接口和泛型类型定义

You may also want this function to find actual concrete types -- i.e., filtering out abstracts, interfaces, and generic type definitions.

public static bool IsRealClass(Type testType)
{
    return testType.IsAbstract == false
         && testType.IsGenericTypeDefinition == false
         && testType.IsInterface == false;
}

这篇关于通过反射接口的实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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