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

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

概述参见英文答案 > Getting all types that implement an interface                                    13个 我想创建一个方法,返回一个类型(或IEnumerable类型),实现一个带有类型参数的特定接口 – 但是我想通过该泛型类型参数本身进行搜索.作为一个例子,这更容易证明: 我想要的方法签名: public IEnu 参见英文答案 > 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();
总结

以上是内存溢出为你收集整理的c# – 通过搜索特定的通用接口参数获取实现通用接口的类型全部内容,希望文章能够帮你解决c# – 通过搜索特定的通用接口参数获取实现通用接口的类型所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/1233004.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-06
下一篇 2022-06-06

发表评论

登录后才能评论

评论列表(0条)

保存