简体   繁体   English

如何在 C# 中使用 flag 属性从枚举中取回位掩码值?

[英]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.在我们的 C# 客户端中,当我们从数据库中检索这个整数值时,我们构造了一个枚举/标志。 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.在我们的应用程序中,我有一个编辑权限页面,然后我使用该页面对不同的枚举值使用按位 OR 来修改此枚举的值。

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.现在,在进行这些更改后,在我的数据库调用中,我需要调用一个需要整数值的更新/插入 sproc。

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:您可以像这样使用 HasFlag():

SellPermissions permissions = SellPermissions.Buy | SellPermissions.Sell;

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

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

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