编程语言
首页 > 编程语言> > c# – “x as X!= null”和“x is X”总是返回相同的结果?

c# – “x as X!= null”和“x is X”总是返回相同的结果?

作者:互联网

是否存在这两个if语句会产生不同结果的情况?

if(x as X != null)
{
  // Do something
}

if(x is X)
{
  // Do something
}

编辑:澄清:我知道操作符(一般)和他们的意思有什么区别.问题是,是否存在这两种情况会产生不同结果的情况.

解决方法:

Is there any situation where these two if statements will produce different results?

首先,请注意,对is的使用有更多限制,因此x可以在(x为X)!= null的情况下编译X.例如,要求指定的类型是引用类型或可空类型;也适用于不可为空的值类型.

现在假设x都是X而(x是X)!= null是有效的表达式.根据C#4.0规范的§7.10.11,“作为T的操作E产生与E相同的结果是T?(T)(E):( T)null”.如果我们将后一个表达式插入(x as X)!= null,我们得到

    (x as X) != null
==  ((x is X) ? (X)x : null) != null  // by the definition of "as"
==  (x is X) ? ((X)x != null) : (null != null)  // distribute
==  (x is X) ? true : false  // because (x is X) implies (x != null)
==  x is X

这证明x是X并且(x作为X)!= null如果两者都是有效表达式则是等价的.

标签:c,operators,net,type-conversion,comparison-operators
来源: https://codeday.me/bug/20190718/1491729.html