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

发布于 2024-09-03 16:39:25 字数 502 浏览 1 评论 0原文

在我们的数据库中,我们有一个位掩码,表示用户可以执行哪些类型的操作。

在我们的 C# 客户端中,当我们从数据库检索这个整数值时,我们构造一个枚举/标志。它看起来有点像下面这样:

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

在我们的应用程序中,我有一个编辑权限页面,然后我使用该页面对不同的枚举值使用按位“或”来修改此枚举的值。

permissions = SellPermisions.Buy | SellPermissions.Sell;

现在,进行这些更改后,在我的数据库调用中,我需要调用一个需要整数值的更新/插入存储过程。

如何从枚举/标志中获取整数按位值,以便可以在数据库中设置修改的权限?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

帅气尐潴 2024-09-10 16:39:25

我可以通过将变量转换为 int 来做到这一点。

int newPermissions = (int)permissions.

I was able to do it by casting the variable to an int.

int newPermissions = (int)permissions.
傾旎 2024-09-10 16:39:25
int permissionsValue = (int) permissions;
int permissionsValue = (int) permissions;
分開簡單 2024-09-10 16:39:25

您可以像这样使用 HasFlag() :

SellPermissions permissions = SellPermissions.Buy | SellPermissions.Sell;

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

You can use HasFlag() like this:

SellPermissions permissions = SellPermissions.Buy | SellPermissions.Sell;

if(permissions.HasFlag(SellPermissions.Sell))
{
    MessageBox.Show("You have Sell permissions");
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文