确定类型是否是泛型类型的子类

5
class Program
{
    static void Main(string[] args) {
        Check(new Foo());
        Check(new Bar());
    }
    static void Check<T>(T obj) {
        // "The type T cannot be used as type parameter..."
        if (typeof(T).IsSubclassOf(typeof(Entity<T>))) {
            System.Console.WriteLine("obj is Entity<T>");
        }
    }
}
class Entity<T> where T : Entity<T>{ }
class Foo : Entity<Foo> { }
class Bar { }

什么是编译此事的适当方法?我可以从非泛型的EntityBase类继承Entity<T>,或者尝试typeof(Entity<>).MakeGenericType(typeof(T)) 并查看是否成功,但是否有一种方式不滥用try { } catch { }块或破坏类型层次结构呢? Type上有一些看起来很有用的方法,例如GetGenericArgumentsGetGenericParameterConstraints,但我完全不知道如何使用它们...

1
可能是重复的问题:检查一个类是否派生自一个泛型类 - Matthew Watson
但是我不知道如何删除/关闭这个问题... - user1096188
实际上,@MatthewWatson 给出的链接中的答案更好。直到现在才看到它。 - Maarten
1个回答

4

类似这样的代码应该可以正常运行。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication4 {
    class Program {
        static void Main(string[] args) {
            Check(new Foo());
            Check(new Bar());
            Console.ReadLine();
        }
        static void Check<T>(T obj) {
            // "The type T cannot be used as type parameter..."
            if (IsDerivedOfGenericType(typeof(T), typeof(Entity<>))) {
                System.Console.WriteLine(string.Format("{0} is Entity<T>", typeof(T)));
            }
        }

        static bool IsDerivedOfGenericType(Type type, Type genericType) {
            if (type.IsGenericType && type.GetGenericTypeDefinition() == genericType)
                return true;
            if (type.BaseType != null) {
                return IsDerivedOfGenericType(type.BaseType, genericType);
            }
            return false;
        }
    }
    class Entity<T> where T : Entity<T> { }
    class Foo : Entity<Foo> { }
    class Bar { }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接