有什么之间的区别|和||还是运营商? [英] What is the difference between the | and || or operators?

查看:117
本文介绍了有什么之间的区别|和||还是运营商?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直使用 || (两个管道)或异位pressions,无论是在C#和PHP。偶尔我看到一个用单管: | 。什么是这两个用途之间的区别?是否有使用一个比其他任何时候警告或者他们可以互换?

I have always used || (two pipes) in OR expressions, both in C# and PHP. Occasionally I see a single pipe used: |. What is the difference between those two usages? Are there any caveats when using one over the other or are they interchangeable?

推荐答案

就像&放大器;和&功放;&安培;操作员,双操作员是一个短路操作符。

Just like the & and && operator, the double Operator is a "short-circuit" operator.

例如:

if(condition1 || condition2 || condition3)

如果条件1为真,条件2和3将不会被选中。

If condition1 is true, condition 2 and 3 will NOT be checked.

if(condition1 | condition2 | condition3)

此将检查条件2和3中,即使1已经真。当你的条件可以是相当昂贵的功能,您可以通过他们获得良好的性能提升。

This will check conditions 2 and 3, even if 1 is already true. As your conditions can be quite expensive functions, you can get a good performance boost by using them.

有一个重要的提醒,NullReferences或类似的问题。例如:

There is one big caveat, NullReferences or similar problems. For example:

if(class != null && class.someVar < 20)

如果类为null,if语句将停止后,阶级!= NULL是假的。如果您只使用&功放;,它会尝试检查class.someVar,你会得到一个不错的NullReferenceException。随着还是运营商可能不是太大的陷阱,因为它是不可能的,你触发了坏事,但它的东西要记住。

If class is null, the if-statement will stop after "class != null" is false. If you only use &, it will try to check class.someVar and you get a nice NullReferenceException. With the Or-Operator that may not be that much of a trap as it's unlikely that you trigger something bad, but it's something to keep in mind.

没有人会使用单&放大器;或者|运营商虽然,除非你有一个设计,其中每一个条件是具有执行的功能。听起来像一个设计的味道,但有时(很少),这是一个干净的方式做的东西。该放大器和;操作者跑这3个功能,如果其中一人返回false,执行else块,而|没有如果没有返回false只运行else块。 - 可能是有用的,但正如所说,往往这是一个设计的气味

No one ever uses the single & or | operators though, unless you have a design where each condition is a function that HAS the be executed. Sounds like a design smell, but sometimes (rarely) it's a clean way to do stuff. The & operator does "run these 3 functions, and if one of them returns false, execute the else block", while the | does "only run the else block if none return false" - can be useful, but as said, often it's a design smell.

还有第二个利用|和&安培;运营商虽然:<一href=\"http://www.c-sharpcorner.com/UploadFile/chandrahundigam/BitWiserOpsInCS11082005050940AM/BitWiserOpsInCS.aspx\">Bitwise操作的。

There is a Second use of the | and & operator though: Bitwise Operations.

这篇关于有什么之间的区别|和||还是运营商?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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