C#relational(>)和Equality(!=)优先级 [英] C# relational (>) and Equality (!=) precedence
本文介绍了C#relational(>)和Equality(!=)优先级的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
您好b $ b在 http://msdn.microsoft。 com / en-us / library / aa691323(v = vs.71).aspx ,给出了
关系(>)的优先级高于Equality(!=)。
所以下面的代码必须抛出NullReferenceException:
表格f = null ;
if (f!= null && f.Width > 10 )
{
}
但它没有抛出任何异常。
请帮助我理解。
解决方案
它不会因为你使用而抛出异常'&&'运算符,它是AND的 short-curcuit 形式:如果第一个布尔操作数为假,很明显AND的结果也是假的,所以第二个运算符不是评估完毕。
如果您使用'&'运算符,则会抛出异常。
你写的是一个非常有效的已知模式来编写快捷方式检查而无需使用第二个if
。基本上,这就是运营商'||'和'&&'的设计目的。
小心操作数导致副作用(可能发生)在布尔函数或属性的情况下):由于这种短路布尔计算,可能无法执行调用。
-SA
Hi
In http://msdn.microsoft.com/en-us/library/aa691323(v=vs.71).aspx, it is given that
relational (>) has higher priority than Equality (!=).
So following code must throw NullReferenceException:
Form f = null;
if (f != null && f.Width > 10)
{
}
But it is not throwing any exception.
Please help me to understand.
解决方案
It will not throw exception because you are using '&&' operator, which is the short-curcuit form of AND: if first Boolean operand is false, it is apparent that the result of AND is also false, so the second operator is not evaluated at all.
If you used '&' operator, it would throw exception.
What you have written is quite a valid known pattern to write shortcut check-ups without a need to use the secondif
. Basically, this is what the operators '||' and '&&' are designed for.
Be careful with the operands causing side effect (which can happen in case of Boolean function or property): the call may not be performed due to this short-circuit Boolean calculation.
—SA
这篇关于C#relational(>)和Equality(!=)优先级的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文