如果是obj.GetType()。IsInstanceOfType(typeof运算(MyClass的))真的吗? [英] When is obj.GetType().IsInstanceOfType(typeof(MyClass)) true?

查看:264
本文介绍了如果是obj.GetType()。IsInstanceOfType(typeof运算(MyClass的))真的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我期待在这片由别人写的代码,我不知道什么时候会评估为true。基本上,跟它SOMETYPE是someOtherType的一个实例。它甚至有意义吗?到目前为止,我已经试过:

I'm looking at this piece of code written by someone else, and I'm wondering when it would evaluate to true. Basically, it is saying someType is an instance of someOtherType. Does it even make sense? So far, I've tried:

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

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

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

和所有的人都评价为假。

And all of them evaluate to false.

任何帮助表示赞赏。

推荐答案

每个那些三线将返回true的如果对象参与( derivedClass 基类 MyClass的分别)为对象,或无证 RuntimeType 对象的实例(请注意,类型是抽象的),因此,例如下列会导致真语句:

Each of those 3 lines will return true only if the object involved (derivedClass, baseClass and myClass respectively) is an instance of object, or of the undocumented RuntimeType object (note that Type is abstract), so for example the following would result in true statements:

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

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

请注意所用的类型(在这种情况下,控制台)并不重要,对语句的结果没有影响。

Note that the type used (in this case Console) doesn't matter and has no effect on the outcome of the statement.

为什么?

有关的文档 IsInstanceOfType 告诉我们,如果传入的对象是当前类型的实例,它将返回true,因此,例如下面的语句将返回true,如果 myForm会是从派生的类表格,否则将返回false。

The documentation for IsInstanceOfType tells us that it will return true if the object passed in is an instance of current type, so for example the following statement will return true if myForm is a class that derives from Form, otherwise it will return false.

typeof(Form).IsInstanceOfType(myForm);

在你的情况 myForm会其实是在的typeof(BaseClass的),这是无证键入 RuntimeType (从键入),所以你只打算让真正返回,如果这没有证件类型发生从提供的类型推导 - 这是不大可能是期望的行为

In your case myForm is in fact typeof(BaseClass), which is of the undocumented type RuntimeType (which derives from Type), and so you are only going to get true returned if this undocumented type happens to derive from the provided type - this is unlikely to be the desired behaviour.

我应该用什么呢?

你是什么人以后可能就是是keword ,该returs真如果提供的对象是给定类型的实例

What you are probably after is the is keword, which returs true if the provided object is an instance of the given type

derivedClass is BaseClass
baseClass is DerivedClass
myClass is MyClass

这篇关于如果是obj.GetType()。IsInstanceOfType(typeof运算(MyClass的))真的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆