简体   繁体   中英

What does a BitWise OR (“|”) mean when used with a return statement?

In C#.NET, has anyone ever seen a return statement inside a method that looks like this?

protected override Buttons GetButtonsToShow()
{
    return Buttons.New | Buttons.Return | Buttons.Delete;
}

How is this BitWise operator "|" working here? What is the result of this statement? I know how the BitWise operators work in if ... else ... statements and such, but I've never seen it used this way.

Buttons is a flags enum .

This makes it bit-mappable where you can use bitwise operators to combine values.

In this case it will returns a value that is a bitmap combining all of the three options.

This blog post has quite a clear explanation (though it uses & for the example).

Logically such methods return set of flags (the enum is marked with Flags attribute). Later you can check whether a certain flag is set using bitwise & .

In this particular example, somewhere there is code that checks whether to show a certain button. Something like this:

Buttons buttons = GetButtonsToShow();

bool showNewButton = (buttons & Buttons.New) != 0;

If you break down this expression it will become more clear:

protected override Buttons GetButtonsToShow()
{
    var returnValue = Buttons.New | Buttons.Return | Buttons.Delete;
    return returnValue;
}

Can you see it now?

The operator | does not alter the return statement itself. The result of the Buttons.New | Buttons.Return | Buttons.Delete Buttons.New | Buttons.Return | Buttons.Delete Buttons.New | Buttons.Return | Buttons.Delete expression is returned by the function.

It is performing the bitwise operations and using the result as the return value. Buttons is an enumeration that has the FlagsAttribute applied to it and looks something like the following:

[Flags]
public enum Buttons
{
    New = 1,
    Return = 2,
    Delete = 4
}

The usage of the return value from your GetButtonsToShow() method would be something like this:

private void DisplayButtons()
{
    var buttons = GetButtonsToShow(); // int value is 7, 1 + 2 + 4

    if ((buttons & Buttons.New) == Buttons.New) // if 7 (111) and 1 (001) equals 1 
    {
        buttonNew.Visible = true;
    }

    // above is for clarity, most likely all buttons visibility is set as:
    // buttonX.Visible = (buttons & Buttons.X) == Buttons.X;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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