请考虑以下代码:
public class A
{
}
public class B : A
{
}
public class C : B
{
}
class D
{
public static bool IsDescendantOf(this System.Type thisType, System.Type thatType)
{
/// ???
}
void Main()
{
A cValue = new C();
C.GetType().IsDescendantOf(cValue.GetType());
}
}
Run Code Online (Sandbox Code Playgroud)
实施IsDescendantOf的最佳方法是什么?
我正在尝试编写验证来检查Object实例是否可以转换为变量Type.我有一个Type实例,用于他们需要提供的对象类型.但类型可能会有所不同.这基本上就是我想要做的.
Object obj = new object();
Type typ = typeof(string); //just a sample, really typ is a variable
if(obj is typ) //this is wrong "is" does not work like this
{
//do something
}
Run Code Online (Sandbox Code Playgroud)
类型对象本身具有IsSubClassOf和IsInstanceOfType方法.但我真正想要检查的是obj是typ的实例还是从typ派生的任何类.
看起来像一个简单的问题,但我似乎无法弄明白.