C#If语句中条件的执行顺序 [英] Execution order of conditions in C# If statement

查看:27
本文介绍了C#If语句中条件的执行顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面有两个 if 语句,它们使用逻辑运算符具有多个条件.逻辑上两者相同,但检查顺序不同.第一个有效,第二个失败.

There are two if statements below that have multiple conditions using logical operators. Logically both are same but the order of check differs. The first one works and the second one fails.

我参考了 MSDN 来检查执行顺序定义的条件;但我找不到.

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?

我曾经使用方法 1,效果很好.寻找一个 MSDN 参考证实使用.

I used to use approach 1 and it works well. Looking for an MSDN reference substantiaing the use.

更新

参考 "短路"评估

代码

  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 &&和 ||运营商短路.那就是:

The && and || operators short-circuit. That is:

1) 如果 &&将其第一个操作数计算为假,它不计算其第二个操作数.

1) If && evaluates its first operand as false, it does not evaluate its second operand.

2) 如果 ||将其第一个操作数评估为真,但不评估其第二个操作数.

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#If语句中条件的执行顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆