我不时会看到如下的枚举:
[Flags]
public enum Options
{
None = 0,
Option1 = 1,
Option2 = 2,
Option3 = 4,
Option4 = 8
}
我不明白[Flags]
- 属性到底是什么。
任何人都可以发布一个很好的解释或示例吗?
答案 0 :(得分:1984)
只要enumerable表示可能值的集合而不是单个值,就应该使用[Flags]
属性。此类集合通常与按位运算符一起使用,例如:
var allowedColors = MyColor.Red | MyColor.Green | MyColor.Blue;
请注意,[Flags]
属性不会自行启用此功能 - 它所做的就是通过.ToString()
方法提供一个很好的表示形式:
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"
同样重要的是要注意[Flags]
不会自动使枚举值的权力为2。如果省略数值,则枚举将不会像在按位运算中所期望的那样工作,因为默认情况下,值以0和递增开头。
声明不正确:
[Flags]
public enum MyColors
{
Yellow, // 0
Green, // 1
Red, // 2
Blue // 3
}
如果以这种方式声明,则值将为黄色= 0,绿色= 1,红色= 2,蓝色= 3.这将使其无法用作标记。
以下是正确声明的示例:
[Flags]
public enum MyColors
{
Yellow = 1,
Green = 2,
Red = 4,
Blue = 8
}
要检索属性中的不同值,可以执行以下操作:
if (myProperties.AllowedColors.HasFlag(MyColor.Yellow))
{
// Yellow is allowed...
}
或在.NET 4之前:
if((myProperties.AllowedColors & MyColor.Yellow) == MyColor.Yellow)
{
// Yellow is allowed...
}
if((myProperties.AllowedColors & MyColor.Green) == MyColor.Green)
{
// Green is allowed...
}
幕后
这是有效的,因为你在枚举中使用了2的幂。在封面下,您的枚举值在二进制和零中看起来像这样:
Yellow: 00000001
Green: 00000010
Red: 00000100
Blue: 00001000
同样,在使用二进制按位OR |
运算符将属性 AllowedColors 设置为红色,绿色和蓝色后, AllowedColors 如下所示:
myProperties.AllowedColors: 00001110
因此,当您检索值时,您实际上是对值进行按位AND &
:
myProperties.AllowedColors: 00001110
MyColor.Green: 00000010
-----------------------
00000010 // Hey, this is the same as MyColor.Green!
无= 0值
关于在枚举中使用0
,引用MSDN:
[Flags]
public enum MyColors
{
None = 0,
....
}
使用None作为其值为零的标志枚举常量的名称。 您不能在按位AND运算中使用None枚举常量来测试标志,因为结果始终为零。但是,您可以执行数值和数值之间的逻辑比较,而不是按位比较。无枚举常量以确定是否设置了数值中的任何位。
您可以在msdn和designing flags at msdn找到有关flags属性及其用法的更多信息
答案 1 :(得分:735)
你也可以这样做
[Flags]
public enum MyEnum
{
None = 0,
First = 1 << 0,
Second = 1 << 1,
Third = 1 << 2,
Fourth = 1 << 3
}
我发现位移比键入4,8,16,32更容易,依此类推。它对您的代码没有影响,因为它全部在编译时完成
答案 2 :(得分:102)
结合答案https://stackoverflow.com/a/8462/1037948(通过位移声明)和https://stackoverflow.com/a/9117/1037948(使用声明中的组合),您可以对先前的值进行位移,而不是使用数字。不一定推荐它,但只是指出你可以。
而不是:
[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,
}
您可以声明
[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确认:
foreach(var e in Enum.GetValues(typeof(Options))) {
string.Format("{0} = {1}", e.ToString(), (byte)e).Dump();
}
结果:
None = 0
One = 1
Two = 2
OneAndTwo = 3
Three = 4
OneTwoAndThree = 7
Four = 8
答案 3 :(得分:48)
请参阅以下示例,其中显示了声明和潜在用法:
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");
}
}
}
}
答案 4 :(得分:34)
我asked recently关于类似事情。
如果您使用标记,则可以向枚举添加扩展方法,以便更轻松地检查包含的标记(请参阅帖子了解详细信息)
这允许你这样做:
[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,
...
}
然后你可以这样做:
PossibleOptions opt = PossibleOptions.OptionOneTwoAndThree
if( opt.IsSet( PossibleOptions.OptionOne ) ) {
//optionOne is one of those set
}
我发现这比查看包含标志的大多数方法更容易阅读。
答案 5 :(得分:26)
在接受答案的扩展中,在C#7中,可以使用二进制文字来编写枚举标志:
[Flags]
public enum MyColors
{
None = 0b0000,
Yellow = 0b0001,
Green = 0b0010,
Red = 0b0100,
Blue = 0b1000
}
我认为这种表示清楚地说明了标志如何在下隐藏。
答案 6 :(得分:22)
@Nidonocu
要向现有值集添加另一个标志,请使用OR赋值运算符。
Mode = Mode.Read;
//Add Mode.Write
Mode |= Mode.Write;
Assert.True(((Mode & Mode.Write) == Mode.Write)
&& ((Mode & Mode.Read) == Mode.Read)));
答案 7 :(得分:18)
添加Mode.Write
:
Mode = Mode | Mode.Write;
答案 8 :(得分:13)
我对if ((x & y) == y)...
构造有些过分冗长,特别是如果x
和y
都是复合标志集,你只想知道是否有任何< / strong>重叠。
在这种情况下,您真正需要知道的是如果在您进行了位屏蔽之后存在非零值[1]。
[1]见Jaime的评论。如果我们真的是 bitmasking ,我们就会 只需检查结果是否为正。但是从
enum
开始 与the[Flags]
attribute结合使用时,甚至可能是消极的, 对于!= 0
而非> 0
的代码而言,它是防御性的。
建立@ andnil的设置...
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();
}
}
}
答案 9 :(得分:11)
标志允许您在枚举中使用位掩码。这允许您组合枚举值,同时保留指定的枚举值。
[Flags]
public enum DashboardItemPresentationProperties : long
{
None = 0,
HideCollapse = 1,
HideDelete = 2,
HideEdit = 4,
HideOpenInNewWindow = 8,
HideResetSource = 16,
HideMenu = 32
}
答案 10 :(得分:5)
在使用标志时,我经常声明其他的None和All项目。这些有助于检查是否设置了所有标志或没有设置标志。
[Flags]
enum SuitsFlags {
None = 0,
Spades = 1 << 0,
Clubs = 1 << 1,
Diamonds = 1 << 2,
Hearts = 1 << 3,
All = ~(~0 << 4)
}
用法:
Spades | Clubs | Diamonds | Hearts == All // true
Spades & Clubs == None // true
答案 11 :(得分:1)
很抱歉,如果有人已经注意到这种情况。我们可以在反射中看到标志的一个完美示例。是Binding Flags ENUM。
[System.Flags]
[System.Runtime.InteropServices.ComVisible(true)]
[System.Serializable]
public enum BindingFlags
用法
// BindingFlags.InvokeMethod
// Call a static method.
Type t = typeof (TestClass);
Console.WriteLine();
Console.WriteLine("Invoking a static method.");
Console.WriteLine("-------------------------");
t.InvokeMember ("SayHello", BindingFlags.InvokeMethod | BindingFlags.Public |
BindingFlags.Static, null, null, new object [] {});
答案 12 :(得分:-2)
当可枚举的值表示 枚举成员。
在这里我们使用按位运算符,和&
示例
[Flags]
public enum Sides { Left=0, Right=1, Top=2, Bottom=3 }
Sides leftRight = Sides.Left | Sides.Right;
Console.WriteLine (leftRight);//Left, Right
string stringValue = leftRight.ToString();
Console.WriteLine (stringValue);//Left, Right
Sides s = Sides.Left;
s |= Sides.Right;
Console.WriteLine (s);//Left, Right
s ^= Sides.Right; // Toggles Sides.Right
Console.WriteLine (s); //Left