C#“或”运算符?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1746302/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 20:26:29  来源:igfitidea点击:

C# 'or' operator?

c#

提问by Jarred Sumner

Is there an oroperator in C#?

orC#中有运算符吗?

I want to do:

我想要做:

if (ActionsLogWriter.Close or ErrorDumpWriter.Close == true)
{
    // Do stuff here
}

But I'm not sure how I could do something like that.

但我不确定我怎么能做这样的事情。

采纳答案by Jeff Sternal

C# supports two boolean oroperators: the single bar |and the double-bar ||.

C# 支持两个布尔or运算符: single bar|和 double-bar ||

The difference is that |always checks both the left and right conditions, while ||only checks the right-side condition if it's necessary (if the left side evaluates to false).

不同之处在于|始终检查左侧和右侧条件,而||仅在必要时检查右侧条件(如果左侧评估为假)。

This is significant when the condition on the right-side involves processing or results in side effects. (For example, if your ErrorDumpWriter.Closemethod took a while to complete or changed something's state.)

当右侧的条件涉及处理或导致副作用时,这很重要。(例如,如果您的ErrorDumpWriter.Close方法需要一段时间才能完成或更改某些状态。)

回答by Dave Barker

if (ActionsLogWriter.Close || ErrorDumpWriter.Close == true)
{    // Do stuff here
}

回答by Jeff Paquette

just like in C and C++, the boolean or operator is ||

就像在 C 和 C++ 中一样,布尔或运算符是 ||

if (ActionsLogWriter.Close || ErrorDumpWriter.Close == true)
{
    // Do stuff here
}

回答by Secko

Or is ||in C#.

或者是||在 C# 中。

You may have a look at this.

你可以看看这个

回答by Josh

Also worth mentioning, in C# the OR operator is short-circuiting. In your example, Close seems to be a property, but if it were a method, it's worth noting that:

还值得一提的是,在 C# 中,OR 运算符是短路的。在您的示例中, Close 似乎是一个属性,但如果它是一个方法,则值得注意的是:

if (ActionsLogWriter.Close() || ErrorDumpWriter.Close())

is fundamentally different from

根本不同于

if (ErrorDumpWriter.Close() || ActionsLogWriter.Close())

In C#, if the first expression returns true, the second expression will not be evaluated at all. Just be aware of this. It actually works to your advantage most of the time.

在 C# 中,如果第一个表达式返回 true,则根本不会计算第二个表达式。请注意这一点。大多数时候它实际上对你有利。

回答by wls223

The single " | " operator will evaluate both sides of the expression.

单个“|”运算符将计算表达式的两边。

    if (ActionsLogWriter.Close | ErrorDumpWriter.Close == true)
{
    // Do stuff here
}

The double operator " || " will only evaluate the left side if the expression returns true.

double 运算符“ || ”将仅在表达式返回 true 时评估左侧。

    if (ActionsLogWriter.Close || ErrorDumpWriter.Close == true)
{
    // Do stuff here
}

C# has many similarities to C++ but their still are differences between the two languages ;)

C# 与 C++ 有很多相似之处,但它们仍然是两种语言之间的差异;)