c# - 如何使用反射返回从泛型子类化的所有类,而不给出特定的泛型类型

标签 c# generics reflection

我正在尝试编写一个使用反射的方法来返回所有类,这些类是使用泛型的类的子类,而不受泛型类型的限制。因此,例如,在 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<>)));
}

关于c# - 如何使用反射返回从泛型子类化的所有类,而不给出特定的泛型类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6426949/

相关文章:

java - 我如何参数化这个 Java 泛型?

swift - 编译器无法推断返回类型

swift - 如何在不创建实例的情况下在 Swift 中获取镜像?

c# - 您可以忽略特定版本的强命名引用吗?

c# - 为什么 C# 中的 DateTime.TryParseExact 没有按预期工作

c# - 在 Java 中创建 T 的新实例

java - 在运行时修改方法注解参数

c++ - 如何将json对象转换为QObject?

c# - App.config 似乎被忽略了

c# - 如何设置/现在DateTime类的日期格式解释?