繁体   English   中英

如何使用反射从泛型返回所有​​类子类,而不提供特定的泛型类型

[英]How can I use reflection to return all classes subclassing from a generic, without giving a specific generic type

我正在尝试使用反射编写一个方法来返回所有类,这些类是使用泛型的类的子类,而不受泛型类型的限制。 例如,在EF中我想找到所有的映射类。 这些类的设置如下:

public class clientMap : EntityTypeConfiguration<Client> {}

我想在我的程序集中找到EntityTypeConfiguration<T>的子类中的所有类,而不是特别指定Client作为T。 我想在我的应用程序中为所有类返回实体类型配置,而不对其进行硬编码。

如果没有泛型,我会循环遍历程序type.IsSubclassOf(typeof(BaseClass))的类型,检查是否type.IsSubclassOf(typeof(BaseClass)) ,但是我不知道在处理泛型时如何做到这一点。

我相信你想要这样的东西:

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;
        }
    }
}

这些测试通过:

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<>)));
}

据我所知,你的情况应该足够了

type.BaseType != null &&
type.BaseType.MetadataToken == typeof(EntityTypeConfiguration<>).MetadataToken

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM