显然,没有。
以下是选项:
Type.IsSubclassOf
正如您已经发现的那样,如果两种类型相同,这将不起作用,这是一个示例 LINQPad 程序演示:
void Main()
{
typeof(Derived).IsSubclassOf(typeof(Base)).Dump();
typeof(Base).IsSubclassOf(typeof(Base)).Dump();
}
public class Base { }
public class Derived : Base { }
输出:
True
False
这表明Derived 是Base 的子类,但Base(显然)不是其自身的子类。
Type.IsAssignableFrom
现在,这将回答您的特定问题,但也会给您带来误报。正如 Eric Lippert 在 cmets 中指出的那样,虽然该方法确实会为上述两个问题返回 True,但它也会为这些问题返回 True,这是您可能不想要的:
void Main()
{
typeof(Base).IsAssignableFrom(typeof(Derived)).Dump();
typeof(Base).IsAssignableFrom(typeof(Base)).Dump();
typeof(int[]).IsAssignableFrom(typeof(uint[])).Dump();
}
public class Base { }
public class Derived : Base { }
在这里你得到以下输出:
True
True
True
最后一个 True 将表明,如果方法仅回答了所提出的问题,uint[] 继承自 int[] 或者它们是同一类型,这显然不是案例。
所以IsAssignableFrom 也不完全正确。
is 和 as
is 和 as 在您的问题上下文中的“问题”是它们将要求您对对象进行操作并直接在代码中编写其中一种类型,而不是使用 Type 对象.
换句话说,这不会编译:
SubClass is BaseClass
^--+---^
|
+-- need object reference here
也不会这样:
typeof(SubClass) is typeof(BaseClass)
^-------+-------^
|
+-- need type name here, not Type object
也不会这样:
typeof(SubClass) is BaseClass
^------+-------^
|
+-- this returns a Type object, And "System.Type" does not
inherit from BaseClass
结论
虽然上述方法可能符合您的需求,但您的问题的唯一正确答案(如我所见)是您需要额外检查:
typeof(Derived).IsSubclassOf(typeof(Base)) || typeof(Derived) == typeof(Base);
这当然在方法中更有意义:
public bool IsSameOrSubclass(Type potentialBase, Type potentialDescendant)
{
return potentialDescendant.IsSubclassOf(potentialBase)
|| potentialDescendant == potentialBase;
}