为什么枚举权限通常有 0、1、2、4 个值? [英] Why do enum permissions often have 0, 1, 2, 4 values?

查看:20
本文介绍了为什么枚举权限通常有 0、1、2、4 个值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么人们总是使用像 0, 1, 2, 4, 8 这样的枚举值而不是 0, 1, 2, 3, 4 ?

Why are people always using enum values like 0, 1, 2, 4, 8 and not 0, 1, 2, 3, 4?

这与位操作等有关吗?

我真的很感谢一个关于如何正确使用它的小示例片段:)

I would really appreciate a small sample snippet on how this is used correctly :)

[Flags]
public enum Permissions
{
    None   = 0,
    Read   = 1,
    Write  = 2,
    Delete = 4
}

推荐答案

因为它们是 2 的幂,我可以这样做:

Because they are powers of two and I can do this:

var permissions = Permissions.Read | Permissions.Write;

也许以后……

if( (permissions & Permissions.Write) == Permissions.Write )
{
    // we have write access
}

它是一个位字段,其中每个设置的位对应于某个权限(或枚举值逻辑上对应的任何内容).如果这些被定义为 1, 2, 3, ... 你将无法以这种方式使用按位运算符并获得有意义的结果.深入研究...

It is a bit field, where each set bit corresponds to some permission (or whatever the enumerated value logically corresponds to). If these were defined as 1, 2, 3, ... you would not be able to use bitwise operators in this fashion and get meaningful results. To delve deeper...

Permissions.Read   == 1 == 00000001
Permissions.Write  == 2 == 00000010
Permissions.Delete == 4 == 00000100

注意到这里的模式了吗?现在,如果我们以我原来的例子,即

Notice a pattern here? Now if we take my original example, i.e.,

var permissions = Permissions.Read | Permissions.Write;

那么……

permissions == 00000011

看到了吗?ReadWrite 位都已设置,我可以独立检查(还要注意 Deletenotem> 设置,因此该值不表示删除权限).

See? Both the Read and Write bits are set, and I can check that independently (Also notice that the Delete bit is not set and therefore this value does not convey permission to delete).

它允许在单个位字段中存储多个标志.

It allows one to store multiple flags in a single field of bits.

这篇关于为什么枚举权限通常有 0、1、2、4 个值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆