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 { }
塊或mauls的類型層次結構?確定類型是否是泛型類型的子類
上有Type
一些方法,看起來像他們可能是有用的,像GetGenericArguments
和GetGenericParameterConstraints
但我對如何使用它們完全一無所知......
可能的重複[檢查一個類是否從泛型類派生](http://stackoverflow.com/questions/457676/check-if-a-class-is-derived-from-a-通用類) –
非常感謝,這回答了 – user1096188
的問題,但我不知道如何刪除/關閉這個問題.... – user1096188