C# 'is' operator Clarification

前端 未结 6 1935
半阙折子戏
半阙折子戏 2021-01-17 21:11

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

相关标签:
6条回答
  • 2021-01-17 21:20

    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.

    0 讨论(0)
  • 2021-01-17 21:20

    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.

    0 讨论(0)
  • 2021-01-17 21:22

    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.

    0 讨论(0)
  • 2021-01-17 21:23

    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;

    0 讨论(0)
  • 2021-01-17 21:28

    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

    0 讨论(0)
  • 2021-01-17 21:30

    From MSDN:

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

    0 讨论(0)
提交回复
热议问题