简体   繁体   中英

How can I get the bitmask value back out of an enum with the flag attribute in C#?

In our database we have a bitmask that represents what types of actions a user can make.

In our C# client when we retrieve this integer value from the database we construct an enum/flag. It looks somewhat like the following:

[Flags]
public enum SellPermissions
{
    Undefined = 0,
    Buy = 1,
    Sell = 2,
    SellOpen = 4,
    SellClose = 8
    // ...
}

In our application I have an edit permissions page which I then use to modify the value of this enum using the bitwise OR on different enum values.

permissions = SellPermisions.Buy | SellPermissions.Sell;

Now, after these changes are made, in my database call I need to call an update/insert sproc which is expecting an integer value.

How do I get the integer bitwise value back out of my enum/flag so I can set the modified permissions in the database?

我能够通过将变量转换为int来实现。

int newPermissions = (int)permissions.
int permissionsValue = (int) permissions;

You can use HasFlag() like this:

SellPermissions permissions = SellPermissions.Buy | SellPermissions.Sell;

if(permissions.HasFlag(SellPermissions.Sell))
{
    MessageBox.Show("You have Sell permissions");
}

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