开发者

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 wh开发者_运维百科ich 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?


I was able to do it by casting the variable to an 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");
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜