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.
Simple mockup:
namespace Program {
class MyGeneric<T> { }
class MyDerived : MyGeneric<String> { }
class Program {
public static void Main() {
MyDerived item = new MyDerived ();
Boolean isIt = typeof(MyGeneric<>).BaseType.IsAssignableFrom (item.GetType());
Console.WriteLine (isIt); // Output: "True"
foreach (Type type in item.GetType().BaseType.GetGenericArguments())
Console.WriteLine(type.Name);
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.