要检查一个类型是不是C#中另外一个类型的子类,很简单: ui
typeof (SubClass).IsSubclassOf(typeof (BaseClass)); // returns true
可是,这将失败: this
typeof (BaseClass).IsSubclassOf(typeof (BaseClass)); // returns false
有没有办法检查类型是不是基类自己的子类OR,而无需使用OR
运算符或扩展方法? spa
typeof(BaseClass).IsAssignableFrom(unknownType);
您应该尝试使用Type.IsAssignableFrom 。 .net
显然没有。 code
选项以下: orm
is
与as
正如您已经发现的,若是两种类型相同,则将没法正常工做,这是一个示例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
(显然)不是其自身的子类。 ip
如今,这将回答您的特定问题,但也会给您带来误报。 正如埃里克·利珀特(Eric Lippert)在评论中指出的那样,尽管该方法对于上述两个问题的确会返回True
,但对于这些问题,也会返回True
,您可能不但愿这样作: get
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; }
我正在发布此答案,但愿有人与我分享是否以及为何这不是一个好主意。 在个人应用程序中,我具备要检查的Type属性,以确保它是typeof(A)或typeof(B),其中B是从A派生的任何类。因此个人代码是:
public class A { } public class B : A { } public class MyClass { private Type _helperType; public Type HelperType { get { return _helperType; } set { var testInstance = (A)Activator.CreateInstance(value); if (testInstance==null) throw new InvalidCastException("HelperType must be derived from A"); _helperType = value; } } }
我以为我在这里可能有点天真,因此欢迎任何反馈。
若是您尝试在Xamarin Forms PCL项目中执行此操做,则上述使用IsAssignableFrom
解决方案会出现错误:
错误:“类型”不包含“ IsAssignableFrom”的定义,找不到能够接受类型“ Type”的第一个参数的扩展方法“ IsAssignableFrom”(您是否缺乏using指令或程序集引用?)
由于IsAssignableFrom
要求提供TypeInfo
对象。 您能够使用System.Reflection
的GetTypeInfo()
方法:
typeof(BaseClass).GetTypeInfo().IsAssignableFrom(typeof(unknownType).GetTypeInfo())