c# – 通过搜索特定的通用接口参数获取实现通用接口的类型
发布时间:2020-12-15 22:49:05 所属栏目:百科 来源:网络整理
导读:参见英文答案 Getting all types that implement an interface????????????????????????????????????13个 我想创建一个方法,返回一个类型(或IEnumerable类型),实现一个带有类型参数的特定接口 – 但是我想通过该泛型类型参数本身进行搜索.作为一个例子,这更
参见英文答案 >
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(); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
推荐文章
站长推荐
热点阅读