[英]Get type that implements generic interface by searching for a specific generic interface parameter
我想创建一个方法,该方法返回一个类型(或 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 。
这与此问题非常相似,但是使用该示例,我想通过IRepository<>
和User
进行搜索。
为了重构@lucky 的答案,我更喜欢将类型与泛型类型定义进行比较,而不是使用类型名称:
static readonly Type GenericIEnumerableType = typeof(IEnumerable<>);
//Find all types that implement IEnumerable<T>
static IEnumerable<T> FindAllEnumerableTypes<T>(Assembly assembly) =>
assembly
.GetTypes()
.Where(type =>
type
.GetInterfaces()
.Any(interf =>
interf.IsGenericType
&& interf.GetGenericTypeDefinition() == GenericIEnumerableType
&& interf.GenericTypeArguments.Single() == typeof(T)));
或者,您可以检查interf
是否可从GenericIEnumerableType.MakeGenericType(typeof(T))
或其他方式分配。
你可以这样试试;
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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.