条件在C#如果语句的执行顺序 [英] Execution order of conditions in C# If statement
问题描述
有两种,如果低于这个语句具有使用逻辑运算符多个条件。从逻辑上都是一样的,但检查的顺序不同。第一个工作,第二个失败。
我提到 MSDN 检查是否执行顺序的规定的条件;但我找不到。
考虑一个多个检查条件&功放;&安培;
的逻辑运算符。它是保证它总是会检查第一个条件,如果不是满足第二个条件会的不可以检查?
我曾经使用方法1和它工作得很好。寻找一个MSDN参考substantiaing使用。
更新
code
名单,其中,串>员工= NULL;
如果(员工= NULL和放大器;!&安培; employees.Count大于0)
{
串theEmployee =员工[0];
}
如果(employees.Count大于0&安培;&安培;员工!= NULL)
{
串theEmployee =员工[0];
}
&将功放;&安培;和||运营商短路。那就是:
1)如果&安培;&安培;评估其第一个操作数为假,它不评价它的第二个操作数。
2)如||评估其第一个操作数为真,不评价它的第二个操作数。
这让你做零检查和放大器;&安培;做点什么对象,因为如果它不为null,第二个操作数不计算。
There are two if statements below that has multiple conditions using logical operators. Logically both are same but the order of check differs. The first one works and the second one fails.
I referred MSDN for checking whether the order of execution of the conditions defined; but I could not find.
Consider a multiple check condition that has &&
as the logical operator. Is it guaranteed that it will always check the first condition and if that is not satisfied the second condition will not be checked?
I used to use approach 1 and it works well. Looking for an MSDN reference substantiaing the use.
UPDATE
Refer "short-circuit" evaluation
CODE
List<string> employees = null;
if (employees != null && employees.Count > 0)
{
string theEmployee = employees[0];
}
if (employees.Count > 0 && employees != null)
{
string theEmployee = employees[0];
}
The && and || operators short-circuit. That is:
1) If && evaluates its first operand as false, it does not evaluate its second operand.
2) If || evaluates its first operand as true, it does not evaluate its second operand.
This lets you do null check && do something with object, as if it is not null the second operand is not evaluated.
这篇关于条件在C#如果语句的执行顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!