[Flags] Enum 属性在 C# 中意味着什么?
有时我会看到如下所示的枚举:
[Flags]
public enum Options
{
None = 0,
Option1 = 1,
Option2 = 2,
Option3 = 4,
Option4 = 8
}
我不明白 [Flags]
属性到底是做什么的。
有人可以发布一个很好的解释或例子吗?
From time to time I see an enum like the following:
[Flags]
public enum Options
{
None = 0,
Option1 = 1,
Option2 = 2,
Option3 = 4,
Option4 = 8
}
I don't understand what exactly the [Flags]
attribute does.
Anyone have a good explanation or example they could post?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(14)
每当可枚举表示可能值的集合而不是单个值时,就应该使用
[Flags]
属性。 此类集合通常与按位运算符一起使用,例如:请注意,
[Flags]
属性本身不能启用此功能 - 它所做的只是允许通过以下方式进行良好的表示:.ToString()
方法:还需要注意的是,
[Flags]
不会自动使枚举值成为 2 的幂。 如果省略数值,则枚举将无法按位运算中的方式工作,因为默认情况下,值从 0 开始并递增。错误的声明:
如果以这种方式声明,这些值将为黄色 = 0、绿色 = 1、红色 = 2、蓝色 = 3。这将使其作为标志无用。
下面是正确声明的一个示例:
要检索属性中的不同值,可以执行以下操作:
或在 .NET 4 之前:
在幕后
这之所以有效,是因为您在枚举中使用了 2 的幂。 在幕后,您的枚举值在二进制 1 和 0 中看起来像这样:
同样,在使用二进制按位 OR
|AllowedColors 设置为 Red、Green 和 Blue 后code> 运算符,AllowedColors 看起来像这样:
因此,当您检索值时,您实际上是在对值执行按位 AND
&
:None = 0 值< /strong>
关于在枚举中使用
0
,引用 MSDN:您可以在 msdn 和 在 msdn 上设计标志
The
[Flags]
attribute should be used whenever the enumerable represents a collection of possible values, rather than a single value. Such collections are often used with bitwise operators, for example:Note that the
[Flags]
attribute doesn't enable this by itself - all it does is allow a nice representation by the.ToString()
method:It is also important to note that
[Flags]
does not automatically make the enum values powers of two. If you omit the numeric values, the enum will not work as one might expect in bitwise operations, because by default the values start with 0 and increment.Incorrect declaration:
The values, if declared this way, will be Yellow = 0, Green = 1, Red = 2, Blue = 3. This will render it useless as flags.
Here's an example of a correct declaration:
To retrieve the distinct values in your property, one can do this:
or prior to .NET 4:
Under the covers
This works because you used powers of two in your enumeration. Under the covers, your enumeration values look like this in binary ones and zeros:
Similarly, after you've set your property AllowedColors to Red, Green and Blue using the binary bitwise OR
|
operator, AllowedColors looks like this:So when you retrieve the value you are actually performing bitwise AND
&
on the values:The None = 0 value
And regarding the use of
0
in your enumeration, quoting from MSDN:You can find more info about the flags attribute and its usage at msdn and designing flags at msdn
当可枚举值表示一组值时,将使用标志
枚举成员。
这里我们使用按位运算符| 和&
示例
<前><代码> [标志]
公共枚举 Sides { 左 = 0,右 = 1,顶部 = 2,底部 = 3 }
边左右 = Sides.Left | 侧面.右;
Console.WriteLine(leftRight);//左、右
字符串 stringValue = leftRight.ToString();
Console.WriteLine(stringValue);//左、右
边 s = Sides.Left;
s |= Sides.Right;
Console.WriteLine(s);//左、右
s ^= Sides.Right; // 切换 Sides.Right
Console.WriteLine(s); //左边
Flags are used when an enumerable value represents a collection of
enum members.
here we use bitwise operators, | and &
Example
标志允许您在枚举中使用位掩码。 这允许您组合枚举值,同时保留指定的枚举值。
Flags allow you to use bitmasking inside your enumeration. This allows you to combine enumeration values, while retaining which ones are specified.
如果有人已经注意到这种情况,我们深表歉意。 我们可以在反射中看到一个完美的标志示例。 是 绑定标志 ENUM 。
使用
Apologies if someone already noticed this scenario. A perfect example of flags we can see in reflection. Yes Binding Flags ENUM.
Usage
对于我来说,关于
if ((x & y) == y)...
构造有些过于冗长,尤其是 ifx
ANDy
都是复合标志集,您只想知道是否有任何重叠。在这种情况下,您真正需要知道的是位屏蔽后是否存在非零值[1]。
以@andnil 的设置为基础......
There's something overly verbose to me about the
if ((x & y) == y)...
construct, especially ifx
ANDy
are both compound sets of flags and you only want to know if there's any overlap.In this case, all you really need to know is if there's a non-zero value[1] after you've bitmasked.
Building off of @andnil's setup...
添加
Mode.Write
:To add
Mode.Write
:定义问题
让我们定义一个表示用户类型的枚举:
我们定义包含三个值的 UserType 枚举:
Customer、Driver 和 Admin。
但是如果我们需要怎么办?代表值的集合?
例如,在一家送货公司,我们知道管理员和司机都是员工。 那么让我们添加一个新的枚举项
Employee
。 稍后,我们将向您展示如何用它来表示管理员和驱动程序:定义并声明标志属性
标志是一个属性,允许我们将枚举表示为值的集合而不是单一的值。 那么,让我们看看如何在枚举上实现 Flags 属性:
我们添加
Flags
属性并用 2 的幂对值进行编号。如果两者都没有,这将无法工作。现在回到我们之前的问题,我们可以使用
|
运算符来表示Employee
:另外,我们可以将其定义为枚举内的常量以直接使用它:
幕后花絮
为了更好地理解
Flags
属性,我们必须回到数字的二进制表示形式。 例如,我们可以将 1 表示为二进制0b_0001
,将 2 表示为0b_0010
:我们可以看到每个值都以有效位表示。 这就是用 2 的幂对值进行编号的想法的由来。 我们还可以注意到,
Employee
包含两个活动位,即它是两个值 Driver 和 Admin 的组合。对标志属性的操作
我们可以使用按位运算符来处理
标志
。初始化一个值
对于初始化,我们应该使用名为 None 的值 0,这意味着集合为空:
现在,我们可以定义一个变量:
添加一个值
我们可以使用
|
运算符添加值:现在,flags 变量等于 Driver。
删除值
我们可以使用
&, ~
运算符删除值:现在,flagsvariable 等于 None。
我们可以使用
&
运算符检查该值是否存在:结果为
False
。另外,我们可以使用
HasFlag
方法来做到这一点:此外,结果将为 False。
正如我们所看到的,使用
&
运算符和HasFlag
方法这两种方法都会给出相同的结果,但是我们应该使用哪一种呢? 为了找到答案,我们将在几个框架上测试性能。衡量性能
首先,我们将创建一个控制台应用程序,并在
.csproj
文件中将TargetFramwork
标记替换为TargetFramworks
标签:其次,我们引入
BenchmarkDotNet
库来获取基准测试结果:我们添加
[SimpleJob(RuntimeMoniker.Net48)]
、[SimpleJob (RuntimeMoniker.NetCoreApp31)]
和[SimpleJob(RuntimeMoniker.Net60)]
属性添加到HasFlagBenchmarker
类,以查看不同版本.NET Framework / .NET Core
:因此,在 .NET Framework 4.8 中,
HasFlag
方法比慢得多位操作符
。 但是,.Net Core 3.1
和.Net 6.0
的性能有所提高。 所以在新版本中,我们可以同时使用这两种方式。Define the Problem
Let’s define an enum that represents the types of users:
We define the UserType enum that contains three values:
Customer, Driver, and Admin.
But what if we need to represent a collection of values?
For example, at a delivery company, we know that both the Admin and the Driver are employees. So let’s add a new enumeration item
Employee
. Later on, we will show you how we can represent both the admin and the driver with it:Define and Declare a Flags Attribute
A Flags is an attribute that allows us to represent an enum as a collection of values rather than a single value. So, let’s see how we can implement the Flags attribute on enumeration:
We add the
Flags
attribute and number the values with powers of 2. Without both, this won’t work.Now going back to our previous problem, we can represent
Employee
using the|
operator:Also, we can define it as a constant inside the enum to use it directly:
Behind the Scenes
To understand the
Flags
attribute better, we must go back to the binary representation of the number. For example, we can represent 1 as binary0b_0001
and 2 as0b_0010
:We can see that each value is represented in an active bit. And this is where the idea of numbering the values with the power of 2 came from. We can also note that
Employee
contains two active bits, that is, it is a composite of two values Driver and Admin.Operations on Flags Attribute
We can use the bitwise operators to work with
Flags
.Initialize a Value
For the initialization, we should use the value 0 named None, which means the collection is empty:
Now, we can define a variable:
Add a Value
We can add value by using
|
operator:Now, the flags variable equals Driver.
Remove a Value
We can remove value by use
&, ~
operators:Now, flagsvariable equals None.
We can check if the value exists by using
&
operator:The result is
False
.Also, we can do this by using the
HasFlag
method:Also, the result will be False.
As we can see, both ways, using the
&
operator and theHasFlag
method, give the same result, but which one should we use? To find out, we will test the performance on several frameworks.Measure the Performance
First, we will create a Console App, and in the
.csproj
file we will replace theTargetFramwork
tag with theTargetFramworks
tag:Secondly, let’s introduce the
BenchmarkDotNet
library to get the benchmark results:We add
[SimpleJob(RuntimeMoniker.Net48)]
,[SimpleJob(RuntimeMoniker.NetCoreApp31)]
, and[SimpleJob(RuntimeMoniker.Net60)]
attributes to theHasFlagBenchmarker
class to see the performance differences between different versions of.NET Framework / .NET Core
:So, in
.NET Framework 4.8
aHasFlag
method was much slower than theBitOperator
. But, the performance improves in.Net Core 3.1
and.Net 6.0
. So in newer versions, we can use both ways.@Nidonocu
要将另一个标志添加到现有值集,请使用 OR 赋值运算符。
@Nidonocu
To add another flag to an existing set of values, use the OR assignment operator.
我最近问过 关于类似的事情。
如果您使用标志,您可以向枚举添加扩展方法,以便更轻松地检查包含的标志(有关详细信息,请参阅帖子)
这允许您执行以下操作:
然后您可以执行以下操作:
我发现这比检查包含的大多数方法更容易阅读旗帜。
I asked recently about something similar.
If you use flags you can add an extension method to enums to make checking the contained flags easier (see post for detail)
This allows you to do:
Then you can do:
I find this easier to read than the most ways of checking the included flags.
请参阅以下示例,了解声明和潜在用法:
Please see the following for an example which shows the declaration and potential usage:
当使用标志时,我经常声明额外的 None 和 All 项目。 这些有助于检查是否设置了所有标志或未设置标志。
用法:
更新 2019-10:
从 C# 7.0 开始,您可以使用二进制文字,这可能更直观地阅读:
When working with flags I often declare additional None and All items. These are helpful to check whether all flags are set or no flag is set.
Usage:
Update 2019-10:
Since C# 7.0 you can use binary literals, which are probably more intuitive to read:
作为对已接受答案的扩展,在 C#7 中,枚举标志可以使用二进制文字来编写:
我认为这种表示形式清楚地表明了标志在幕后如何工作。
In extension to the accepted answer, in C#7 the enum flags can be written using binary literals:
I think this representation makes it clear how the flags work under the covers.
您也可以这样做,
我发现位移比输入 4、8、16、32 等更容易。 它对您的代码没有影响,因为这一切都是在编译时完成的
You can also do this
I find the bit-shifting easier than typing 4,8,16,32 and so on. It has no impact on your code because it's all done at compile time
结合答案 https://stackoverflow.com/a/8462/1037948 (通过位移位声明)和 https://stackoverflow.com/a/9117/1037948(在声明中使用组合)您可以对以前的值进行位移动,而不是使用数字。 不一定推荐它,但只是指出你可以。
而不是:
您可以声明
使用 LinqPad 确认:
结果为:
Combining answers https://stackoverflow.com/a/8462/1037948 (declaration via bit-shifting) and https://stackoverflow.com/a/9117/1037948 (using combinations in declaration) you can bit-shift previous values rather than using numbers. Not necessarily recommending it, but just pointing out you can.
Rather than:
You can declare
Confirming with LinqPad:
Results in: