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

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

问题描述

为什么人们总是使用类似 0,1,2,4,8 ,而不是 0,1,2,3,4枚举值



有这事做位操作等。?



我会很感激这个是如何使用的一个小样本的片断正确:)

  [国旗] 
公共枚举权限
{
无= 0,
读= 1,
写= 2,
删除= 4
}


解决方案

由于他们是两个大国,我可以做到这一点:

  VAR的权限= Permissions.Read | Permissions.Write; 

和也许以后...

  IF((权限和​​放大器; Permissions.Write)== Permissions.Write)
{
//我们有写入权限
}

这是一个位字段,其中每组位对应于某种许可(或任何枚举值逻辑上对应)。如果这些被定义为 1,2,3,... 您将无法以这种方式使用位运算符,并得到有意义的结果。要深入研究...

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

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

  VAR的权限= Permissions.Read | Permissions.Write; 



然后...

 权限== 00000011 

看到了吗?无论是位设置,我可以独立检查(另请注意,删除位的的设置,所以这个值不传达权限删除)。



它允许一个多个标志中存储比特的单个字段


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

Has this something to do with bit operations, etc.?

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
}

解决方案

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

var permissions = Permissions.Read | Permissions.Write;

And perhaps later...

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

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;

Then...

permissions == 00000011

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天全站免登陆