简体   繁体   中英

C# 'is' operator Clarification

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, eg 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.

An is expression evaluates to true if the provided expression is non-null, and the provided object can be cast to the provided type without causing an exception to be thrown.

Source

From MSDN :

An is expression evaluates to true if [...] expression can be cast to type

http://msdn.microsoft.com/en-us/library/scekt9xw%28v=vs.80%29.aspx

An is expression evaluates to true if the provided expression is non-null, and the provided object can be cast to the provided type without causing an exception to be thrown.

is indicate if the object can be casted to a class or interface.

If you have a BaseClass and a SubClass then:

var obj = new SubClass();

obj is SubClass returns true;

obj is BaseClass also returns true;

if(something is X) checks if the underlying type of something is X . This is significantly different from checking if a type supports casting to X since many types can support casts to X without being of type X .

Conversely the as operator attempts a conversion to a particular type and assigns null if source type is not within the inheritance chain of the target type.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM