dimanche 12 juin 2016

IsSubclassOf() does not work for a child whose parent is generic, unless generic type is specified

Given the following classes:

class A<T> { ... }
class B1: A<int> { ... }
class B2: A<string> { ... }
class C: B1 { ... }
class D: B2 { ... }

We have the following results:

typeof(C).IsSubclassOf(typeof(A<>))        // returns false
typeof(C).IsSubclassOf(typeof(A<int>)   // returns true

Now, the question is, what if we don't know what the generic type of B is. How can we determine then, whether our type descends from the base generic class A<> or not?

bool IsDescebdedFromA(object x)
{
   return typeof(x).IsSubclassOf(typeof(A<>));    // does not give correct result. we have to specify generic type.
}

Thanks already





Aucun commentaire:

Enregistrer un commentaire