【问题标题】:When is obj.GetType().IsInstanceOfType(typeof(MyClass)) true?obj.GetType().IsInstanceOfType(typeof(MyClass)) 何时为真?
【发布时间】:2012-08-28 21:59:17
【问题描述】:

我正在查看其他人编写的这段代码,我想知道它何时会评估为 true。基本上,它说 someType 是 someOtherType 的一个实例。它甚至有意义吗?到目前为止,我已经尝试过:

derivedClass.GetType().IsInstanceOfType(typeof(BaseClass)) 

baseClass.GetType().IsInstanceOfType(typeof(DerivedClass)) 

myClass.GetType().IsInstanceOfType(typeof(MyClass)) 

并且所有这些都评估为假。

感谢任何帮助。

【问题讨论】:

  • 您可能想要重构并使用is 运算符。
  • typeof 返回一个对象System.Type,这就是为什么它总是假的。把它改成derivedClass is BaseClass 会好很多。

标签: c# types isinstance


【解决方案1】:

IsInstanceOfType() 检查您传递给它的 instance 是否是您调用它的类型的实例。

您将System.Type 实例传递给IsInstanceOfType()。只有在 typeof(Type) 或其基类之一上调用它时才会如此。

【讨论】:

  • 你的意思是myClass.GetType().IsInstanceOfType(typeof(Type))
  • @user1486691:否。typeof(Type).IsInstanceOfType(anyType) 将返回 true 任何 Type instance。 IsInstanceOfType 不应该接受类型。
  • typeof(DateTime).IsInstanceOfType(new DateTime()): true
【解决方案2】:

如果所涉及的对象(分别为derivedClassbaseClassmyClass)是 object 或未记录的 @ 的实例,则这 3 行中的每一行都将返回 true 987654328@ 对象(注意Type 是抽象的),因此例如以下将导致正确的陈述:

var myObject = new object();
myObject.GetType().IsInstanceOfType(typeof(Console));

myObject = typeof(Object);
myObject.GetType().IsInstanceOfType(typeof(Console));

请注意,使用的类型(在本例中为 Console)无关紧要,对语句的结果没有影响。

为什么?

IsInstanceOfType 的文档告诉我们,如果传入的对象是当前类型的实例,它将返回 true,例如,如果 myForm 是派生自 Form 的类,则以下语句将返回 true , 否则返回 false。

typeof(Form).IsInstanceOfType(myForm);

在您的情况下,myForm 实际上是 typeof(BaseClass),它属于未记录的类型 RuntimeType(派生自 Type),因此您只会在此未记录类型的情况下返回 true碰巧从提供的类型派生 - 这不太可能是所需的行为。

我应该改用什么?

你可能想要的是 is keword,如果提供的对象是给定类型的实例,则返回 true

derivedClass is BaseClass
baseClass is DerivedClass
myClass is MyClass

【讨论】:

  • 我相信你混淆了 IsAssignableFrom 和 IsInstanceOfType。您的代码在询问“此 Type 类型的对象是 Type 类型的实例吗?”这将永远是真的。 'is' 关键字不能总是使用,因为有时你有一个类型的对象。
【解决方案3】:

Type.IsInstanceOf documentation 表示 Type.IsInstanceOfType(o) 返回 "true 如果当前 Type 在由 o 表示的对象的继承层次结构中>,或者当前 Typeo 支持的接口。”

在上面的例子中,TypeGetType()返回的类型,所以它是最左边的对象的类型。对象otypeof(BaseClass),它的类型是Type。当前的TypeDerivedClass,对象otypeof(BaseClass)o 的类型是Type

将其插入文档中。如果DerivedClassType 的继承层次结构中,则返回“true”。

这很少是真的。

作者几乎可以肯定是指typeof(BaseClass).IsInstanceOfType(derivedClass),更容易写成derivedClass is BaseClass

【讨论】:

    【解决方案4】:

    当您调用 GetType() 的对象是作为参数传递给 IsInstanceOfType() 方法的参数的 System.Type 对象的实例时,这是正确的。

    【讨论】:

      【解决方案5】:

      IsInstanceOfType判断指定对象是否为当前Type的实例。

      示例:IsInstanceOfType(o)

      如果当前 Type 在 o 表示的对象的继承层次结构中,或者当前 Type 是 o 支持的接口,则为 true。如果这些条件都不满足,或者 o 为 null,或者当前 Type 是开放的泛型类型,则为 false

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-06-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多