一、.Net基础【1.3】AndAlso & OrElse Operators in C#短路运算符
AndAlso(&&)
辑运算符 AndAlso 和 OrElse 表现称为“短路”的行为。短路运算符首先计算左侧表达式。如果左侧表达式使整个表达式为假(在 AndAlso 中)或验证(在 OrElse 中)整个表达式,则程序执行过程继续,而不计算右侧表达式。
同样,如果使用 OrElse 的逻辑表达式中左侧表达式计算为 True,则执行过程继续下一行代码,而不计算第二个表达式,因为第一个表达式已经启用整个表达式。
AndAlso 运算符
对两个表达式执行简化逻辑合取。
备注
如果编译的代码可以根据一个表达式的计算结果跳过对另一表达式的计算,则将该逻辑运算称为“短路”。如果第一个表达式的计算结果可以决定运算的最终结果,则不需要计算另一个表达式,因为它不会更改最终结果。如果跳过的表达式很复杂或涉及过程调用,则短路可以提高性能。
OrElse 运算符
用于对两个表达式执行短路逻辑析取。
如果编译的代码可以根据一个表达式的计算结果跳过对另一表达式的计算,则将该逻辑运算称为“短路”。如果第一个表达式的计算结果可以决定运算的最终结果,则不需要计算另一个表达式,因为它不会更改最终结果。如果跳过的表达式很复杂或涉及过程调用,则短路可以提高性能。
The logical operator && is the AndAlso in C#. This is used to connect two logical conditions checking like if (<condition1> && <condition2>). In this situation both conditions want to be true for passing the logic. Looking at the e.g. below
int a = 100;
int b = 0;
if (b > 0 && a/b <100)
{
Console.Write("ok");
}
The point here is, the condition "b > 0" will check first. Because "b > 0" a false condition, second condition "a/b <100" won't need to check and our "&&" operator won't perform the second condition checking. So actually our execution time is saving in a logical operation in which more conditions are combined using "&&" operator.
And(&)
The difference of "&" operator compared to above is mentioned below
int a = 100;
int b = 0;
if (b > 0 & a/b <100)
{
Console.Write("ok");
}
The point here is, the condition "b > 0" will check first. Because "b > 0" a false condition, second condition "a/b <100" won't need to check. But our "&" operator will perform the second condition checking also. So actually our execution time is losing for a useless checking. Also executing the "a/b <100" unless b>0 is generating an error also. So got the point?
Or(|) and OrElse(||)
The difference of Or ("|") and OrElse ("||") are also similar to "And" operators, as first one will check all conditions and second one won't execute remaining logical checking, if it's found any of the previous checking is true and saving time. You can analysis these by the below code.
//Or
if (b > 0 | a/b <100)
{
Console.Write("ok");
}
//OrElse
if (b >= 0 || a/b <100)
{
Console.Write("ok");
}