【问题标题】:How can I use reflection to return all classes subclassing from a generic, without giving a specific generic type如何使用反射返回从泛型继承的所有类,而不给出特定的泛型类型
【发布时间】:2011-06-21 22:56:07
【问题描述】:

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

public class clientMap : EntityTypeConfiguration<Client> {}

我想在我的程序集中查找属于EntityTypeConfiguration&lt;T&gt; 的子类的所有类,而不是专门将Client 指定为T。我想返回应用程序中所有类的实体类型配置而不对其进行硬编码。

如果没有泛型,我会遍历程序集中的类型,检查是否type.IsSubclassOf(typeof(BaseClass)),但是在处理泛型时我不确定如何执行此操作。

【问题讨论】:

标签: c# generics reflection


【解决方案1】:

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

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

【讨论】:

  • openGenericType 在实际代码中应该是什么? EntityTypeConfiguration&lt;&gt; 或者括号里应该有什么?
  • 对于您的情况,typeof(EntityTypeConfiguration&lt;&gt;)。请注意代码和测试清楚地说明了这一点。
  • 好风格,Contracts 是一种好方法,应该鼓励使用它(命名空间)。我发现这比控制台应用程序示例的答案更有用。
【解决方案2】:

据我了解您的情况,以下应该足够了

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

【讨论】:

    猜你喜欢
    • 2015-08-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-01
    • 1970-01-01
    • 2011-08-19
    • 2018-09-27
    相关资源
    最近更新 更多