c# - 如果 if 结构的第一部分为假,会发生什么?

标签 c# if-statement

我想知道当程序处理具有多个条件的 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 operation x & y, except that y is evaluated only if x is not false.
  • The operation x || y corresponds to the operation x | y, except that y is evaluated only if x is not true.

关于c# - 如果 if 结构的第一部分为假,会发生什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2864500/

相关文章:

javascript - 通过javascript打印多个文件

mysql - 如何在node.js中的mysql包中设置IF条件

c# - 如何为数组中的对象创建事件?

C# + SQL Server - 将新行读入内存的最快/最有效的方法

c++ - 一种不使用 if 语句评估阈值的方法

bash - awk大于小于但在设定范围内

java - 优雅地替代开关结构

jquery - 检查 url 的一部分

c# - 如何在 C# 中清理/隐藏敏感数据

c# - 将 List<double> 转换为 LiveCharts.IChartValues