简体   繁体   English

“ | =”运算符在C#中做什么?

[英]What does the “|=” operator do in C#?

I've recently come across some code that I don't fully understand. 我最近遇到了一些我不太了解的代码。 Below is a basic representation of this code: 以下是此代码的基本表示形式:

bool flag = false;
flag |= someFunction();

In this example, someFunction() is a function that returns a bool value. 在此示例中, someFunction()是返回bool值的函数。 My question is, what does the | 我的问题是,什么是| = operator do? =运算符吗?

I haven't found much information regarding |= on the web or in this community. 在网络上或在这个社区中,我没有找到太多关于|=信息。 I understand basic assignment operations using the = operator, comparison operations using the = = operator or the other variants, but I've never seen |= used in an assignment before. 我了解使用=运算符的基本赋值操作,使用= =运算符或其他变体的比较操作,但是我从未见过|=在赋值中使用过。

I also know that the | 我也知道| operator is used for a bitwise inclusive OR comparison. 运算符用于按位“ OR比较。 However, it doesn't make sense to me to use this as part of an assignment. 但是,将其用作作业的一部分对我来说没有任何意义。 In sudo code it seems that the code above is saying "If the result of a bitwise inclusive OR between "flag" and someFunction() results in a true value, assign the true value to flag. Otherwise, assign the value of false to flag." 在sudo代码中,似乎上面的代码在说:“如果“ flag”和someFunction()之间按位“或”的结果导致为true,则将true值分配给flag。否则,将false的值分配给flag ”。 Of course, if either flag or someFunction() stored/returned a true value then the result would be true (based on how a bitwise inclusive OR works). 当然,如果标志或someFunction()存储/返回了真值,则结果将为真(基于按位“或”运算的结果)。

Is this a correct interpretation? 这是正确的解释吗? If that is how |= works, since I know that "flag" is false does it really make any sense to use the |= operator as opposed to a simple = assignment operator in this scenario? 如果这是|=工作方式,那么由于我知道“ flag”为假,在这种情况下使用|=运算符而不是简单的=赋值运算符真的有意义吗?

Thanks in advance. 提前致谢。

You are correct that = would have the same effect in your case. 您是正确的, =在您的情况下将具有相同的效果。

In general, if there are several such conditions, the first one may use |= simply for consistency, but it has no technical advantage here. 通常,如果存在多个这样的条件,则第一个条件可能只是为了保持一致性而使用|= ,但在此没有技术优势。

flag |= someFunction() is equivalent to flag = flag | someFunction(); flag |= someFunction()等同于flag = flag | someFunction(); flag = flag | someFunction();
This is the OR assignment operator. 这是OR赋值运算符。

Please see MSDN for more details. 有关更多详细信息,请参见MSDN

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

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