C#'is'运算符说明 [英] C# 'is' operator Clarification

查看:48
本文介绍了C#'is'运算符说明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

is 运算符是否指示对象是某个类的实例,还是仅当可以将其强制转换那堂课?

假设我有一个名为 command DbCommand ,它实际上已经被初始化为 SqlCommand . command is OracleCommand 的结果是什么?

( SqlCommand OracleCommand 均从 DbCommand 继承)

解决方案

它将检查对象是否是该类型的成员,或者是从基本类型或接口继承或实现基本类型或接口的类型.在某种程度上,它会检查对象是否可以转换为上述类型.

命令是OracleCommand 返回false,因为它是 SqlCommand ,而不是 OracleCommand .但是,由于 command是SqlCommand command是DbCommand 都将返回true,因为它是这两种类型的成员,因此可以分别向下转换或向上转换.

如果您具有三个继承级别,例如 BaseClass SubClass SubSubClass ,初始化为 new SubClass()的对象仅对 is返回trueBaseClass 是SubClass .尽管 SubSubClass 都是从这两个派生的,但是对象本身不是它的实例,因此 SubSubClass 返回false.

Does the is operator indicate whether or not an object is an instance of a certain class, or only if it can be casted to that class?

Assume I have a DbCommand called command that has actually has been initialized as a SqlCommand. What is the result of command is OracleCommand?

(SqlCommand and OracleCommand both inherit from DbCommand)

解决方案

It checks if the object is a member of that type, or a type that inherits from or implements the base type or interface. In a way, it does check if the object can be cast to said type.

command is OracleCommand returns false as it's an SqlCommand, not an OracleCommand. However, both command is SqlCommand and command is DbCommand will return true as it is a member of both of those types and can therefore be downcast or upcast to either respectively.

If you have three levels of inheritance, e.g. BaseClass, SubClass and SubSubClass, an object initialized as new SubClass() only returns true for is BaseClass and is SubClass. Although SubSubClass derives from both of these, the object itself is not an instance of it, so is SubSubClass returns false.

这篇关于C#'is'运算符说明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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