jeudi 12 mai 2016

Determine if object is an instance of a generic base class, any generic type

I need to test if a value is an instance of a generic base class, without knowing the generic type parameter. Using the MSDN example as the base of my example, this is what I'd like to accomplish:

using System;

public class Class1<T> { }
public class DerivedC1 : Class1<int> { }

class IsSubclassTest
{
   public static void Main()
   {
      Console.WriteLine(
          "DerivedC1 subclass of Class1: {0}",
          typeof(DerivedC1).IsSubclassOf(typeof(Class1<>)) // <- Here.
      );
   }
}

While this is syntactically correct, it always yields false. If I remove the generic type parameter, it works as expected (returns true).

How can I test if a class type is a subclass of a generic base class, without knowing its generic type parameter as such?





Aucun commentaire:

Enregistrer un commentaire