我想知道当程序处理具有多个条件的 if 结构时会发生什么。我有一个想法,但我不确定。我举个例子:
List<string> myTestList = null;
if (myTestList != null && myTestList.Count > 0)
{
//process
}
列表为空。在处理if语句时,是否会从左到右,一条件不成立就退出if?
我已经试过了,似乎没有抛出任何错误,所以我假设上面的解释是对的,但我不确定。
最佳答案
重要的是&&
。这是短路,所以永远不会计算 Count
;从左到右评估条件。
还有一个非短路运算符(&
),但在 if 测试中非常很少见;它主要用于按位运算(在 int
等上)。
来自规范:
Conditional logical operators
The
&&
and||
operators are called the conditional logical operators. They are also called the “short-circuiting” logical operators....
The
&&
and||
operators are conditional versions of the&
and|
operators:
- The operation
x && y
corresponds to the operationx & y
, except thaty
is evaluated only ifx
is notfalse
.- The operation
x || y
corresponds to the operationx | y
, except thaty
is evaluated only ifx
is nottrue
.
关于c# - 如果 if 结构的第一部分为假,会发生什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2864500/