如何确定Type是否为RunTimeType?
如何确定Type是否为RunTimeType类型? 我有这个工作,但它有点kludgy:
private bool IsTypeOfType(Type type) { return type.FullName == "System.RuntimeType"; }
我猜你真的想知道Type
对象是否描述了Type
类,但Type
对象是typeof(RuntimeType)
而不是typeof(Type)
,因此将它与typeof(Type)
进行比较失败。
您可以做的是检查Type
对象描述的Type
实例是否可以分配给Type
的变量。 这给出了期望的结果,因为RuntimeType
派生自Type
:
private bool IsTypeOfType(Type type) { return typeof(Type).IsAssignableFrom(type); }
如果您确实需要知道描述Type
类的Type
对象,则可以使用GetType方法:
private bool IsRuntimeType(Type type) { return type == typeof(Type).GetType(); }
但是,因为typeof(Type) != typeof(Type).GetType()
,你应该避免这种情况。
例子:
IsTypeOfType(typeof(Type)) // true IsTypeOfType(typeof(Type).GetType()) // true IsTypeOfType(typeof(string)) // false IsTypeOfType(typeof(int)) // false IsRuntimeType(typeof(Type)) // false IsRuntimeType(typeof(Type).GetType()) // true IsRuntimeType(typeof(string)) // false IsRuntimeType(typeof(int)) // false
return type == typeof(MyObjectType) || isoftype(type.BaseType) ;