[英]Do “x as X != null” and “x is X” always return the same result?
Is there any situation where these two if statements will produce different results? 是否存在这两个if语句会产生不同结果的情况?
if(x as X != null)
{
// Do something
}
if(x is X)
{
// Do something
}
Edit: To clarify: I know what is the difference between the operators (in general) and what they mean. 编辑:澄清:我知道运营商(一般)和他们的意思有什么区别。 The question is if there is any situation where these two would produce different results. 问题是,是否存在这两种情况会产生不同结果的情况。
There functionally is no difference between the 2 statements. 功能上两个语句之间没有区别。 In general the as
version is used to avoid a double type test because you can do the following 通常, as
版本用于避免双重类型测试,因为您可以执行以下操作
var local = x as X;
if (local != null) {
// Sweet I have local!
}
vs. 与
if (x is X) {
// This runs the type check yet again
var local = (X)x;
}
If you aren't actually using the value after the type test then just use the is
version 如果您实际上没有在类型测试后使用该值,那么只需使用is
版本
If x
is a non-nullable type (or a generic type not constrained to be a nullable type) then the first option won't compile; 如果x
是非可空类型(或者不限制为可空类型的泛型类型),则第一个选项将不会编译; the second is the only option. 第二个是唯一的选择。
Beyond that, they're the same. 除此之外,他们是一样的。
Is there any situation where these two if statements will produce different results? 是否存在这两个if语句会产生不同结果的情况?
First, note that there are more restrictions on the use of as
than of is
, so x is X
may compile in cases where (x as X) != null
may not. 首先,请注意,有对使用更多的限制as
比is
,所以x is X
的情况下可以编译其中(x as X) != null
不得。 For example, as
requires that the specified type be a reference type or a nullable type; 例如, as
需要,该指定类型是引用类型或可空类型; is
works with non-nullable value types as well. is
适用于不可为空的值类型。
Assume now that both x is X
and (x as X) != null
are valid expressions. 现在假设x is X
而(x as X) != null
是有效的表达式。 According to §7.10.11 of the C# 4.0 specification, "the operation E as T
produces the same result as E is T ? (T)(E) : (T)null
". 根据C#4.0规范的§7.10.11,“ E as T
的操作E as T
产生与E is T ? (T)(E) : (T)null
相同的结果E is T ? (T)(E) : (T)null
”。 If we plug that latter expression into (x as X) != null
, we get 如果我们将后一个表达式插入(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
This proves that x is X
and (x as X) != null
are equivalent if both are valid expressions. 这证明x is X
并且(x as X) != null
如果两者都是有效表达式则是等价的。
In this case: 在这种情况下:
if(x as X != null)
{
// Do something
}
You are first attempting to cast x
to type X
before comparing to null (ie whether the cast succeeded or not). 您首先尝试将x
为类型X
然后再与null进行比较(即转换是否成功)。
In this other case: 在另一个案例中:
if(x is X)
{
// Do something
}
You are simply asking whether x
is of type X
and no casting is done. 您只是询问x
是否为X
类型并且没有进行转换。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.