简体   繁体   English

为什么短路操作员不是默认操作员

[英]Why aren't short circuited operators the default

Given that a typical coding mantra is "Don't induce side effects in method calls." 鉴于典型的编码原则是“不要在方法调用中引起副作用”。 and that the only reason (that I know off - please enlighten me if I'm wrong) to not use short circuited operators is when you depend on the side effects of a method call in subsequent code. 并且不使用短路运算符的唯一原因(我知道,如果不对,请告诉我)是当您依赖后续代码中方法调用的副作用时。 Why isn't the default operator in languages like C# and VB.NET not a short circuited version? 为什么C#和VB.NET等语言中的默认运算符不是短路版本?

IE: IE浏览器:

 if (Method1() & Method2()) {
 }

 if Method1 And Method2 then
 End if

 if (Method1() | Method2()) {
 }

 if Method1 Or Method2 then
 End if

Would actually (by default) mean 实际上(默认情况下)是指

 if (Method1() && Method2()) {
 }

 if Method1 AndAlso Method2 then
 End if

 if (Method1() || Method2()) {
 }

 if Method1 OrElse Method2 then
 End if

Well there are two different reasons and two different answers I think. 我认为有两个不同的原因和两个不同的答案。

For C# (and most Related older languages) the single ampersand or single pipe actually does bitwise operations against variables (bitwise as opposed to logical). 对于C# (和大多数相关的较旧语言),单个&号或单个管道实际上针对变量执行按位运算(按位而不是逻辑)。 That's why in all C/C++ code when someone wants a logical and you will see the double ampersand in their code. 这就是为什么在所有C / C ++代码中,当有人想要逻辑时,您会在他们的代码中看到双“&”号的原因。

For VB.NET I believe the answer is just history. 对于VB.NET,我相信答案只是历史。 Legacy Basic languages have always used "and" and "or" to do non-short circuit operations. 旧版基本语言始终使用“和”和“或”来进行非短路操作。 It was an extremely poor decision but it's been carried all the way up to VB.NET. 这是一个非常糟糕的决定,但一直一直延续到VB.NET。

It does bear mentioning that all the Basic languages utilize the "and/or" keywords to do bitwise operations as well. 值得一提的是,所有基本语言都使用“和/或”关键字来进行按位运算。 In older Basics there was no equivelant of the AndAlso or OrElse keywords to force short circuit so you had to nest If statements to get the logical equivelant of a short circuit and. 在较早的Basics中,没有与AndAlso或OrElse关键字等价的词来强制短路,因此您必须嵌套If语句才能获得与and的逻辑等价词。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM