简体   繁体   English

C#中的“| =”运算符是什么?

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

In researching the cause of a bug, I came across this line of code: 在研究错误的原因时,我遇到了这行代码:

Status |= (int)states.Reading;

What is the "|=" operator in C#? C#中的“| =”运算符是什么?

"Status" is defined thusly: 因此“状态”定义如下:

public static int Status 

...with an accessor and mutator (or "getter" and "setter"), while "states" is defined this way: ...使用存取器和mutator(或“getter”和“setter”),而“states”以这种方式定义:

[Flags]
public  enum states

It's the "bitwise logical OR" operator, as defined here. 它是“按位逻辑OR”运算符,如此处所定义

x |= y is equivalent to x = x | y x |= y等于x = x | y x = x | y

Also, if you want to learn more about the "|" 另外,如果您想了解更多关于“|”的信息 operator itself, you can do so here. 操作员本身,你可以在这里这样做

While using the enumerators if you have specified [Flags] attribute on top of an "enum" member, this enables the user to select more than one enumerators in a single go. 如果您在“enum”成员之上指定了[Flags]属性,则使用枚举器时,这使用户可以一次性选择多个枚举器。 What I mean is this:- 我的意思是: -

if this is your enumerator:- 如果这是你的普查员: -

[Serializable, DataContract(Namespace = "Company.Domain.LOB.Handler")]
[Flags]
public enum BankItemStatus
{
    [EnumMember]
    UnBatched,
    [EnumMember]
    Batched,
    [EnumMember]
    Sent,
    [EnumMember]
    ReplyReceived,
    [EnumMember]
    Closed
}

Now if you use the Enum like this:- 现在如果你像这样使用Enum: -

BankItemStatus bankItemStatus = BankItemStatus.UnBatched;
BankItemStatus bankItemStatus = BankItemStatus.Sent;

The final value preserved by bankItemStatus would be BankItemStatus.Sent. bankItemStatus保存的最终值是BankItemStatus.Sent。 You can check it like this:- 您可以这样检查: -

if(bankItemStatus.UnBatched==BankItemStatus.UnBatched) //FALSE
if(bankItemStatus.Sent==BankItemStatus.Sent) //TRUE

Now if you do it like this:- 现在,如果你这样做: -

BankItemStatus bankItemStatus = BankItemStatus.UnBatched;
bankItemStatus |= bankItemStatus.Sent

You will see that bankItemStatus now has both the enum members. 您将看到bankItemStatus现在同时具有枚举成员。 You can check it like this:- 您可以这样检查: -

if(bankItemStatus.UnBatched==BankItemStatus.UnBatched) //TRUE
if(bankItemStatus.Sent==BankItemStatus.Sent) //TRUE

Hope that helps in understanding the use of |= operator in C# (in context of Enumerators). 希望有助于理解在C#中使用| =运算符(在枚举器的上下文中)。

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

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