参见英文答案 >
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();