• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

一、.Net基础【1.3】AndAlso&OrElseOperatorsinC#短路运算符

原作者: [db:作者] 来自: [db:来源] 收藏 邀请
AndAlso(&&)
辑运算符 AndAlso 和 OrElse 表现称为“短路”的行为。短路运算符首先计算左侧表达式。如果左侧表达式使整个表达式为假(在 AndAlso 中)或验证(在 OrElse 中)整个表达式,则程序执行过程继续,而不计算右侧表达式。
同样,如果使用 OrElse 的逻辑表达式中左侧表达式计算为 True,则执行过程继续下一行代码,而不计算第二个表达式,因为第一个表达式已经启用整个表达式。

对两个表达式执行简化逻辑合取。
备注
如果编译的代码可以根据一个表达式的计算结果跳过对另一表达式的计算,则将该逻辑运算称为“短路”。如果第一个表达式的计算结果可以决定运算的最终结果,则不需要计算另一个表达式,因为它不会更改最终结果。如果跳过的表达式很复杂或涉及过程调用,则短路可以提高性能。

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");
}

鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
关于从C#中获取json格式的字符串中的某个值发布时间:2022-07-13
下一篇:
C#:MVC打印PDF文件发布时间:2022-07-13
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap