微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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

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

如果没有泛型,我会循环遍历程序集中的类型,检查是否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<>)));
}

原文地址:https://www.jb51.cc/csharp/91944.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐