c# – 通过搜索特定的通用接口参数获取实现通用接口的类型

参见英文答案 > Getting all types that implement an interface                                    13个
我想创建一个方法,返回一个类型(或IEnumerable类型),实现一个带有类型参数的特定接口 – 但是我想通过该泛型类型参数本身进行搜索.作为一个例子,这更容易证明:

我想要的方法签名:

public IEnumerable<Type> GetByInterfaceAndGeneric(Type interfaceWithParam,Type specificTypeParameter)

如果我有下面的对象

public interface IRepository<T> { };
  public class FooRepo : IRepository<Foo> { };
  public class DifferentFooRepo : IRepository<Foo> {};

然后我希望能够做到:

var repos = GetByInterfaceAndGeneric(typeof(IRepository<>),typeof(Foo));

并获得包含类型FooRepo和DifferentFooRepo的IEnumerable.

这与this question非常相似,但是使用该示例我想通过IRepository<>进行搜索.并由用户.

解决方法

你可以这样试试;

public static IEnumerable<Type> GetByInterfaceAndGeneric(Type interfaceWithParam,Type specificTypeParameter)
    {
        var query =  
            from x in specificTypeParameter.Assembly.GetTypes()
            where 
            x.GetInterfaces().Any(k => k.Name == interfaceWithParam.Name && 
            k.Namespace == interfaceWithParam.Namespace && 
            k.GenericTypeArguments.Contains(specificTypeParameter))
            select x;
        return query;
    }

用法;

var types = GetByInterfaceAndGeneric(typeof(IRepository<>),typeof(Foo)).ToList();

相关文章

目录简介使用JS互操作使用ClipLazor库创建项目使用方法简单测...
目录简介快速入门安装 NuGet 包实体类User数据库类DbFactory...
本文实现一个简单的配置类,原理比较简单,适用于一些小型项...
C#中Description特性主要用于枚举和属性,方法比较简单,记录...
[TOC] # 原理简介 本文参考[C#/WPF/WinForm/程序实现软件开机...
目录简介获取 HTML 文档解析 HTML 文档测试补充:使用 CSS 选...