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
上有一些看起来很有用的方法,例如GetGenericArguments
和GetGenericParameterConstraints
,但我完全不知道如何使用它们...