2013-06-12 155 views
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一些方法,看起來像他們可能是有用的,像GetGenericArgumentsGetGenericParameterConstraints但我對如何使用它們完全一無所知......

+1

可能的重複[檢查一個類是否從泛型類派生](http://stackoverflow.com/questions/457676/check-if-a-class-is-derived-from-a-通用類) –

+0

非常感謝,這回答了 – user1096188

+0

的問題,但我不知道如何刪除/關閉這個問題.... – user1096188

回答

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 { } 
}