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 { }
编译这个东西的正确方法是什么?我可以继承Entity<T>
来自非通用 EntityBase
类,或者可以尝试 typeof(Entity<>).MakeGenericType(typeof(T))
看看它是否成功,但有没有办法不滥用 try { } catch { }
阻止或破坏类型层次结构?
关于Type
有一些方法看起来很有用,比如 GetGenericArguments
和 GetGenericParameterConstraints
但我完全不知道如何使用它们......
最佳答案
这样的事情应该可行。
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 { }
}
关于c# - 确定类型是否是泛型类型的子类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17058697/