[英]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>
我有一组类: 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. 所有MyBaseClass<T>
, SomeOtherBaseClass
和SomeCompletelyOtherBaseClass<T>
都继承自相同的基类,但是我对此不感兴趣。
Also as the input for my code, I have a Reflected Type ( System.Type
). 同样作为代码输入,我有一个Reflected Type(反射类型( System.Type
))。
What I want to find out is for my Reflected Type - which one of these generic base classes it inherits. 我想找到的是我的Reflected Type-它继承了这些通用基类之一。
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. 我知道可以使用IS运算符或IsAssignableFrom
,但是在这种情况下,我不知道泛型是什么。
So I can't just say myType.IsAssignableFrom(MyBaseClass<T>)
, as I don't know about the T
, all I have is MyBaseClass
name. 所以我不能只说myType.IsAssignableFrom(MyBaseClass<T>)
,因为我不知道T
,所以我只有MyBaseClass
名称。
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. 我要摆脱的是-能够在switch / case语句中使用它,即对于从MyBaseClass继承的所有类都这样做,对于从SomeCompletelyOtherBaseClass继承的所有类都这样做。
Any ideas? 有任何想法吗?
I will however need to identify that the T
is later down the line, so any additional input welcome. 但是,我将需要确定T
在后面,因此欢迎任何其他输入。
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);
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.