参见英文答案 >
Getting all types that implement an interface 13个
我想创建一个方法,返回一个类型(或IEnumerable类型),实现一个带有类型参数的特定接口 – 但是我想通过该泛型类型参数本身进行搜索.作为一个例子,这更容易证明:
我想创建一个方法,返回一个类型(或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();
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。