标志和<<在枚举上操作? C#

时间:2016-06-21 05:55:17

标签: c# enums bit-manipulation

好的,所以我是C#的新手,对于我的生活,我无法理解下面的代码(来自遗留项目)应该做什么:

[Flags]
public enum EAccountStatus
{
    None = 0,
    FreeServiceApproved = 1 << 0,
    GovernmentAccount = 1 << 1,
    PrivateOrganisationAccount = 1 << 2,
    All = 8
}

<<运算符在枚举中到底做了什么?为什么我们需要这个?

2 个答案:

答案 0 :(得分:6)

在幕后,枚举实际上是一个int <<Bitwise Left Shift Operator 编写此代码的等效方法是:

[Flags]
public enum EAccountStatus
{
    None = 0,
    FreeServiceApproved = 1,
    GovernmentAccount = 2,
    PrivateOrganisationAccount = 4,
    All = 8
}

请注意,此枚举具有Flag attribute

如msdn所述:

  

仅在a时使用FlagsAttribute自定义属性进行枚举   按位操作(AND,OR,EXCLUSIVE OR)将在a上执行   数值。

这样,如果您想设置多个选项,可以使用:

var combined =  EAccountStatus.FreeServiceApproved  | EAccountStatus.GovernmentAccount 

相当于:

  00000001  // =1 - FreeServiceApproved 
| 00000010  // =2 - GovernmentAccount 
 ---------
  00000011  //= 3 - FreeServiceApproved  and  GovernmentAccount 

this SO threadflags attribute

有一个很好的解释

答案 1 :(得分:2)

<<正在做什么,即Shift左操作。

why in an enum而言,它只是一种评估表达式作为枚举的方法允许表达式(并在编译时评估它们