2013-06-12 12 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 { } 

Qual è il modo corretto di compilare questa cosa? Potrei sottoclasse lo Entity<T> da una classe non generica EntityBase, o potrei semplicemente provare a typeof(Entity<>).MakeGenericType(typeof(T)) e vedere se ci riesce, ma c'è un modo che non abusa dei blocchi o manda la gerarchia dei tipi?Determinare se type è una sottoclasse di tipo generico

Ci sono alcuni metodi su Type che osservano come potrebbero essere utili, come GetGenericArguments e GetGenericParameterConstraints ma sono totalmente all'oscuro di come usarli ...

+1

possibile duplicato del [Controllare se una classe è derivata da una classe generica] (http://stackoverflow.com/questions/457676/check-if-a-class-is-derived-from-a- generico-classe) –

+0

molte grazie, che risponde alla domanda – user1096188

+0

ma non ho idea di come eliminare/chiudere questa domanda .... – user1096188

risposta

4

Qualcosa del genere dovrebbe funzionare.

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