What does the [Flags] Enum Attribute mean in C#?
有时我会看到如下枚举:
1 2 3 4 5 6 7 8 9 | [Flags] public enum Options { None = 0, Option1 = 1, Option2 = 2, Option3 = 4, Option4 = 8 } |
我不明白
有人能给出一个很好的解释或例子吗?
每当可枚举表示可能值的集合而不是单个值时,应使用
1 | var allowedColors = MyColor.Red | MyColor.Green | MyColor.Blue; |
请注意,
1 2 3 4 5 6 7 8 9 | enum Suits { Spades = 1, Clubs = 2, Diamonds = 4, Hearts = 8 } [Flags] enum SuitsFlags { Spades = 1, Clubs = 2, Diamonds = 4, Hearts = 8 } ... var str1 = (Suits.Spades | Suits.Diamonds).ToString(); //"5" var str2 = (SuitsFlags.Spades | SuitsFlags.Diamonds).ToString(); //"Spades, Diamonds" |
还需要注意的是,
声明不正确:
1 2 3 4 5 6 7 8 | [Flags] public enum MyColors { Yellow, // 0 Green, // 1 Red, // 2 Blue // 3 } |
如果以这种方式声明,值将为黄色=0、绿色=1、红色=2、蓝色=3。这将使其作为标志无效。
以下是正确声明的示例:
1 2 3 4 5 6 7 8 | [Flags] public enum MyColors { Yellow = 1, Green = 2, Red = 4, Blue = 8 } |
要检索属性中的不同值,可以执行以下操作:
1 2 3 4 | if (myProperties.AllowedColors.HasFlag(MyColor.Yellow)) { // Yellow is allowed... } |
或在.NET 4之前:
1 2 3 4 5 6 7 8 9 | if((myProperties.AllowedColors & MyColor.Yellow) == MyColor.Yellow) { // Yellow is allowed... } if((myProperties.AllowedColors & MyColor.Green) == MyColor.Green) { // Green is allowed... } |
在盖子下面
这是因为在枚举中使用了2的幂。在封面下,枚举值的二进制1和0如下所示:
1 2 3 4 | Yellow: 00000001 Green: 00000010 Red: 00000100 Blue: 00001000 |
同样,在使用二进制位或
1 | myProperties.AllowedColors: 00001110 |
因此,当您检索值时,实际上对这些值执行位和
1 2 3 4 | myProperties.AllowedColors: 00001110 MyColor.Green: 00000010 ----------------------- 00000010 // Hey, this is the same as MyColor.Green! |
无=0值
关于在您的枚举中使用
1 2 3 4 5 6 | [Flags] public enum MyColors { None = 0, .... } |
Use None as the name of the flag enumerated constant whose value is zero. You cannot use the None enumerated constant in a bitwise AND operation to test for a flag because the result is always zero. However, you can perform a logical, not a bitwise, comparison between the numeric value and the None enumerated constant to determine whether any bits in the numeric value are set.
您可以在msdn上找到关于flags属性及其用法的更多信息,并在msdn上设计标志。
你也可以这样做
1 2 3 4 5 6 7 8 9 | [Flags] public enum MyEnum { None = 0, First = 1 << 0, Second = 1 << 1, Third = 1 << 2, Fourth = 1 << 3 } |
我发现比特移位比键入4、8、16、32等更容易。它对您的代码没有影响,因为它都是在编译时完成的。
结合答案https://stackoverflow.com/a/8462/1037948(通过位移位声明)和https://stackoverflow.com/a/9117/1037948(在声明中使用组合),您可以位移以前的值,而不是使用数字。不一定要推荐,只要指出你可以。
而不是:
1 2 3 4 5 6 7 8 9 10 11 12 13 | [Flags] public enum Options : byte { None = 0, One = 1 << 0, // 1 Two = 1 << 1, // 2 Three = 1 << 2, // 4 Four = 1 << 3, // 8 // combinations OneAndTwo = One | Two, OneTwoAndThree = One | Two | Three, } |
你可以申报
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | [Flags] public enum Options : byte { None = 0, One = 1 << 0, // 1 // now that value 1 is available, start shifting from there Two = One << 1, // 2 Three = Two << 1, // 4 Four = Three << 1, // 8 // same combinations OneAndTwo = One | Two, OneTwoAndThree = One | Two | Three, } |
与LinqPad确认:
1 2 3 | foreach(var e in Enum.GetValues(typeof(Options))) { string.Format("{0} = {1}", e.ToString(), (byte)e).Dump(); } |
结果:
1 2 3 4 5 6 7 | None = 0 One = 1 Two = 2 OneAndTwo = 3 Three = 4 OneTwoAndThree = 7 Four = 8 |
请参阅以下示例,以了解声明和潜在用法:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | namespace Flags { class Program { [Flags] public enum MyFlags : short { Foo = 0x1, Bar = 0x2, Baz = 0x4 } static void Main(string[] args) { MyFlags fooBar = MyFlags.Foo | MyFlags.Bar; if ((fooBar & MyFlags.Foo) == MyFlags.Foo) { Console.WriteLine("Item has Foo flag set"); } } } } |
我最近问过类似的问题。
如果使用标志,可以将扩展方法添加到枚举中,以使检查包含的标志更容易(有关详细信息,请参阅post)
这允许您执行以下操作:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | [Flags] public enum PossibleOptions : byte { None = 0, OptionOne = 1, OptionTwo = 2, OptionThree = 4, OptionFour = 8, //combinations can be in the enum too OptionOneAndTwo = OptionOne | OptionTwo, OptionOneTwoAndThree = OptionOne | OptionTwo | OptionThree, ... } |
然后你可以做:
1 2 3 4 5 | PossibleOptions opt = PossibleOptions.OptionOneTwoAndThree if( opt.IsSet( PossibleOptions.OptionOne ) ) { //optionOne is one of those set } |
我发现这比检查包含标志的大多数方法更容易阅读。
作为接受答案的扩展,在C 7中,可以使用二进制文字编写枚举标志:
1 2 3 4 5 6 7 8 9 | [Flags] public enum MyColors { None = 0b0000, Yellow = 0b0001, Green = 0b0010, Red = 0b0100, Blue = 0b1000 } |
我认为这个表示法清楚地说明了旗子是如何在封面下工作的。
@ Nidonocu
要向现有值集添加另一个标志,请使用或赋值运算符。
1 2 3 4 5 | Mode = Mode.Read; //Add Mode.Write Mode |= Mode.Write; Assert.True(((Mode & Mode.Write) == Mode.Write) && ((Mode & Mode.Read) == Mode.Read))); |
增加
1 | Mode = Mode | Mode.Write; |
对于
在这种情况下,您真正需要知道的是,在您被位屏蔽之后,是否有一个非零值[1]。
[1] See Jaime's comment. If we were authentically bitmasking, we'd
only need to check that the result was positive. But sinceenum s
can be negative, even, strangely, when combined with the[Flags]
attribute,
it's defensive to code for!= 0 rather than> 0 .
以@andnil的设置为基础…
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace BitFlagPlay { class Program { [Flags] public enum MyColor { Yellow = 0x01, Green = 0x02, Red = 0x04, Blue = 0x08 } static void Main(string[] args) { var myColor = MyColor.Yellow | MyColor.Blue; var acceptableColors = MyColor.Yellow | MyColor.Red; Console.WriteLine((myColor & MyColor.Blue) != 0); // True Console.WriteLine((myColor & MyColor.Red) != 0); // False Console.WriteLine((myColor & acceptableColors) != 0); // True // ... though only Yellow is shared. Console.WriteLine((myColor & MyColor.Green) != 0); // Wait a minute... ;^D Console.Read(); } } } |
标记允许您在枚举内使用位屏蔽。这允许您组合枚举值,同时保留指定的枚举值。
1 2 3 4 5 6 7 8 9 10 11 | [Flags] public enum DashboardItemPresentationProperties : long { None = 0, HideCollapse = 1, HideDelete = 2, HideEdit = 4, HideOpenInNewWindow = 8, HideResetSource = 16, HideMenu = 32 } |
使用标记时,我经常声明附加的"无"和"所有"项。这些有助于检查是否设置了所有标志或未设置任何标志。
1 2 3 4 5 6 7 8 9 10 11 12 13 | [Flags] enum SuitsFlags { None = 0, Spades = 1 << 0, Clubs = 1 << 1, Diamonds = 1 << 2, Hearts = 1 << 3, All = ~(~0 << 4) } |
用途:
1 2 | Spades | Clubs | Diamonds | Hearts == All // true Spades & Clubs == None // true |