mardi 27 janvier 2015

In C#, How do you find out whether an Object is of a Generic Base Type

As a part of writing of a code generation tool (client library for my classes), I found an interesting problem.


I have a set of classes: SomeClass : MyBaseClass<SomeClass> SomeOtherClass : SomeOtherBaseClass ClassC : SomeCompletelyOtherBaseClass<SomeClass>


All of MyBaseClass<T>, SomeOtherBaseClass and SomeCompletelyOtherBaseClass<T> inherit from the same base class, but I'm not interested in that one.


Also as the input for my code, I have a Reflected Type (System.Type).


What I want to find out is for my Reflected Type - which one of these generic base classes it inherits.


I know it's possible to use the IS operator, or IsAssignableFrom, but in this case I don't know what the generic type is.


So I can't just say myType.IsAssignableFrom(MyBaseClass<T>), as I don't know about the T, all I have is MyBaseClass name.


What I want to get out of this is - be able to use it in a switch/case statement, saying that for all classes inheriting from MyBaseClass do this, for all inheriting from SomeCompletelyOtherBaseClass do that.


Any ideas?


I will however need to identify that the T is later down the line, so any additional input welcome.






Aucun commentaire:

Enregistrer un commentaire