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

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

问题描述

如何在 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天全站免登陆