如何使用反射返回从一个普通的子类化的所有类,而不给特定的泛型类型 [英] How can I use reflection to return all classes subclassing from a generic, without giving a specific generic type
问题描述
我想写使用反射来回报那些使用泛型类的子类的所有类,而不被泛型类型的限制的方法。因此,例如,在EF我想找到所有的映射类。这些类是像设置:
I am trying to write a method using reflection to return all classes that are subclasses of a class that uses generics, without being limited by the generic type. So for example, in EF I want to find all mapping classes. The classes are setup like:
public class clientMap : EntityTypeConfiguration<Client> {}
我想找到我的程序集的所有类即是子类 EntityTypeConfiguration< T>
,而不指定客户端
为T明确。我想返回我的应用程序的所有类的实体类型配置而不硬编码。
I want to find all classes in my assembly that is a subclass of of EntityTypeConfiguration<T>
, without specifying Client
as T specifically. I want to return the entity type configuration for all classes in my application without hardcoding it.
没有泛型我将通过在装配的各类循环,检查 type.IsSubclassOf(typeof运算(BaseClass的))
,但我不知道如何与仿制药打交道时做到这一点。
Without generics I would loop through the types in the assembly, check if type.IsSubclassOf(typeof(BaseClass))
, however I am not sure how to do this when dealing with generics.
推荐答案
我相信你想要的东西是这样的:
I believe that you want something like this:
static class TypeExtensions {
public static bool IsDerivedFromOpenGenericType(
this Type type,
Type openGenericType
) {
Contract.Requires(type != null);
Contract.Requires(openGenericType != null);
Contract.Requires(openGenericType.IsGenericTypeDefinition);
return type.GetTypeHierarchy()
.Where(t => t.IsGenericType)
.Select(t => t.GetGenericTypeDefinition())
.Any(t => openGenericType.Equals(t));
}
public static IEnumerable<Type> GetTypeHierarchy(this Type type) {
Contract.Requires(type != null);
Type currentType = type;
while (currentType != null) {
yield return currentType;
currentType = currentType.BaseType;
}
}
}
这些测试通过:
These tests pass:
class Foo<T> { }
class Bar : Foo<int> { }
class FooBar : Bar { }
[Fact]
public void BarIsDerivedFromOpenGenericFoo() {
Assert.True(typeof(Bar).IsDerivedFromOpenGenericType(typeof(Foo<>)));
}
[Fact]
public void FooBarIsDerivedFromOpenGenericFoo() {
Assert.True(typeof(FooBar).IsDerivedFromOpenGenericType(typeof(Foo<>)));
}
[Fact]
public void StringIsNotDerivedFromOpenGenericFoo() {
Assert.False(typeof(string).IsDerivedFromOpenGenericType(typeof(Foo<>)));
}
这篇关于如何使用反射返回从一个普通的子类化的所有类,而不给特定的泛型类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!