System.FlagsAttribute 类
本文提供了此 API 参考文档的补充说明。
该 FlagsAttribute 特性指示可以将枚举视为位字段;即一组标志。
位字段通常用于可能组合出现的元素列表,而枚举常量通常用于互斥元素的列表。 因此,位字段设计为与按位 OR
运算组合以生成未命名的值,而枚举常量则不是。 与枚举常量相比,语言使用的位字段不同。
FlagsAttribute 的属性
AttributeUsageAttribute 应用于此类,其 Inherited 属性指定 false
。 此属性只能应用于枚举。
FlagsAttribute 和枚举指南
FlagsAttribute仅当对数值执行按位运算(AND、OR、EXCLUSIVE OR)时,才对枚举使用自定义属性。
定义两个(即 1、2、4、8 等)的枚举常量。 这意味着组合枚举常量中的单个标志不会重叠。
请考虑为常用标志组合创建枚举常量。 例如,如果你有用于包含枚举常量的文件 I/O 操作的
Read = 1
枚举,请考虑Write = 2
创建枚举常量,该常量ReadWrite = Read OR Write
合并Read
了和Write
标志。 此外,在某些情况下,用于合并标志的按位 OR 操作可能被视为不需要简单任务的高级概念。如果将负数定义为标志枚举常量,请使用警告,因为许多标志位置可能设置为 1,这可能会导致代码混乱,并鼓励编码错误。
一种在数值中设置标志的简便方法是在数值和标志枚举常量之间执行按位 AND 运算,该常量将数值中的所有位设置为零,而该标志与标志不对应,然后测试该操作的结果是否等于标志枚举常量。
用作
None
其值为零的标志枚举常量的名称。 不能在按位 AND 操作中使用None
枚举常量来测试标志,因为结果始终为零。 但是,可以执行数值与None
枚举常量之间的逻辑而不是按位比较,以确定是否设置了数值中的任何位。如果创建值枚举而不是标志枚举,仍值得创建枚举
None
常量。 原因是默认情况下,用于枚举的内存由公共语言运行时初始化为零。 因此,如果未定义值为零的常量,则枚举将在创建时包含非法值。如果应用程序需要表示明显的默认情况,请考虑使用枚举常量,其值为零来表示默认值。 如果没有默认情况,请考虑使用值为零的枚举常量,这意味着其他任何枚举常量不表示的情况。
不要只定义枚举值以镜像枚举本身的状态。 例如,不要定义仅标记枚举末尾的枚举常量。 如果需要确定枚举的最后一个值,请显式检查该值。 此外,如果范围中的所有值有效,则可以对第一个和最后一个枚举常量执行范围检查。
请勿指定为将来使用保留的枚举常量。
定义将枚举常量作为值的方法或属性时,请考虑验证该值。 原因是,即使枚举中未定义数值,也可以将数值强制转换为枚举类型。
示例
下面的示例演示了属性FlagsAttribute
的使用,并显示了对声明使用FlagsAttribute
Enum方法的影响ToString。
using System;
class Example
{
// Define an Enum without FlagsAttribute.
enum SingleHue : short
{
None = 0,
Black = 1,
Red = 2,
Green = 4,
Blue = 8
};
// Define an Enum with FlagsAttribute.
[Flags]
enum MultiHue : short
{
None = 0,
Black = 1,
Red = 2,
Green = 4,
Blue = 8
};
static void Main()
{
// Display all possible combinations of values.
Console.WriteLine(
"All possible combinations of values without FlagsAttribute:");
for (int val = 0; val <= 16; val++)
Console.WriteLine("{0,3} - {1:G}", val, (SingleHue)val);
// Display all combinations of values, and invalid values.
Console.WriteLine(
"\nAll possible combinations of values with FlagsAttribute:");
for (int val = 0; val <= 16; val++)
Console.WriteLine("{0,3} - {1:G}", val, (MultiHue)val);
}
}
// The example displays the following output:
// All possible combinations of values without FlagsAttribute:
// 0 - None
// 1 - Black
// 2 - Red
// 3 - 3
// 4 - Green
// 5 - 5
// 6 - 6
// 7 - 7
// 8 - Blue
// 9 - 9
// 10 - 10
// 11 - 11
// 12 - 12
// 13 - 13
// 14 - 14
// 15 - 15
// 16 - 16
//
// All possible combinations of values with FlagsAttribute:
// 0 - None
// 1 - Black
// 2 - Red
// 3 - Black, Red
// 4 - Green
// 5 - Black, Green
// 6 - Red, Green
// 7 - Black, Red, Green
// 8 - Blue
// 9 - Black, Blue
// 10 - Red, Blue
// 11 - Black, Red, Blue
// 12 - Green, Blue
// 13 - Black, Green, Blue
// 14 - Red, Green, Blue
// 15 - Black, Red, Green, Blue
// 16 - 16
open System
// Define an Enum without FlagsAttribute.
type SingleHue =
| None = 0
| Black = 1
| Red = 2
| Green = 4
| Blue = 8
// Define an Enum with FlagsAttribute.
[<Flags>]
type MultiHue =
| None = 0
| Black = 1
| Red = 2
| Green = 4
| Blue = 8
// Display all possible combinations of values.
printfn "All possible combinations of values without FlagsAttribute:"
for i = 0 to 16 do
printfn $"{i,3} - {enum<SingleHue> i:G}"
// Display all combinations of values, and invalid values.
printfn "\nAll possible combinations of values with FlagsAttribute:"
for i = 0 to 16 do
printfn $"{i,3} - {enum<MultiHue> i:G}"
// The example displays the following output:
// All possible combinations of values without FlagsAttribute:
// 0 - None
// 1 - Black
// 2 - Red
// 3 - 3
// 4 - Green
// 5 - 5
// 6 - 6
// 7 - 7
// 8 - Blue
// 9 - 9
// 10 - 10
// 11 - 11
// 12 - 12
// 13 - 13
// 14 - 14
// 15 - 15
// 16 - 16
//
// All possible combinations of values with FlagsAttribute:
// 0 - None
// 1 - Black
// 2 - Red
// 3 - Black, Red
// 4 - Green
// 5 - Black, Green
// 6 - Red, Green
// 7 - Black, Red, Green
// 8 - Blue
// 9 - Black, Blue
// 10 - Red, Blue
// 11 - Black, Red, Blue
// 12 - Green, Blue
// 13 - Black, Green, Blue
// 14 - Red, Green, Blue
// 15 - Black, Red, Green, Blue
// 16 - 16
Module Example
' Define an Enum without FlagsAttribute.
Enum SingleHue As Short
None = 0
Black = 1
Red = 2
Green = 4
Blue = 8
End Enum
' Define an Enum with FlagsAttribute.
<Flags()>
Enum MultiHue As Short
None = 0
Black = 1
Red = 2
Green = 4
Blue = 8
End Enum
Sub Main()
' Display all possible combinations of values.
Console.WriteLine(
"All possible combinations of values without FlagsAttribute:")
For val As Integer = 0 To 16
Console.WriteLine("{0,3} - {1:G}", val, CType(val, SingleHue))
Next
Console.WriteLine()
' Display all combinations of values, and invalid values.
Console.WriteLine(
"All possible combinations of values with FlagsAttribute:")
For val As Integer = 0 To 16
Console.WriteLine( "{0,3} - {1:G}", val, CType(val, MultiHue))
Next
End Sub
End Module
' The example displays the following output:
' All possible combinations of values without FlagsAttribute:
' 0 - None
' 1 - Black
' 2 - Red
' 3 - 3
' 4 - Green
' 5 - 5
' 6 - 6
' 7 - 7
' 8 - Blue
' 9 - 9
' 10 - 10
' 11 - 11
' 12 - 12
' 13 - 13
' 14 - 14
' 15 - 15
' 16 - 16
'
' All possible combinations of values with FlagsAttribute:
' 0 - None
' 1 - Black
' 2 - Red
' 3 - Black, Red
' 4 - Green
' 5 - Black, Green
' 6 - Red, Green
' 7 - Black, Red, Green
' 8 - Blue
' 9 - Black, Blue
' 10 - Red, Blue
' 11 - Black, Red, Blue
' 12 - Green, Blue
' 13 - Black, Green, Blue
' 14 - Red, Green, Blue
' 15 - Black, Red, Green, Blue
' 16 - 16
前面的示例定义了两个与颜色相关的枚举, SingleHue
以及 MultiHue
。 后者具有特性 FlagsAttribute
;前者不具有此属性。 该示例显示当一系列整数(包括不表示枚举类型的基础值的整数)转换为枚举类型及其显示的字符串表示形式时的行为差异。 例如,请注意,不能将 3 表示为值 SingleHue
,因为 3 不是任何 SingleHue
成员的基础值,而该 FlagsAttribute
属性使可以将 3 表示为 MultiHue
值 Black, Red
。
下面的示例定义另一个具有 FlagsAttribute
特性的枚举,并演示如何使用按位逻辑和相等运算符来确定是否在枚举值中设置了一个或多个位字段。 还可以使用 Enum.HasFlag 该方法执行此操作,但此示例中未显示此方法。
using System;
[Flags]
public enum PhoneService
{
None = 0,
LandLine = 1,
Cell = 2,
Fax = 4,
Internet = 8,
Other = 16
}
public class Example1
{
public static void Main()
{
// Define three variables representing the types of phone service
// in three households.
var household1 = PhoneService.LandLine | PhoneService.Cell |
PhoneService.Internet;
var household2 = PhoneService.None;
var household3 = PhoneService.Cell | PhoneService.Internet;
// Store the variables in an array for ease of access.
PhoneService[] households = { household1, household2, household3 };
// Which households have no service?
for (int ctr = 0; ctr < households.Length; ctr++)
Console.WriteLine("Household {0} has phone service: {1}",
ctr + 1,
households[ctr] == PhoneService.None ?
"No" : "Yes");
Console.WriteLine();
// Which households have cell phone service?
for (int ctr = 0; ctr < households.Length; ctr++)
Console.WriteLine("Household {0} has cell phone service: {1}",
ctr + 1,
(households[ctr] & PhoneService.Cell) == PhoneService.Cell ?
"Yes" : "No");
Console.WriteLine();
// Which households have cell phones and land lines?
var cellAndLand = PhoneService.Cell | PhoneService.LandLine;
for (int ctr = 0; ctr < households.Length; ctr++)
Console.WriteLine("Household {0} has cell and land line service: {1}",
ctr + 1,
(households[ctr] & cellAndLand) == cellAndLand ?
"Yes" : "No");
Console.WriteLine();
// List all types of service of each household?//
for (int ctr = 0; ctr < households.Length; ctr++)
Console.WriteLine("Household {0} has: {1:G}",
ctr + 1, households[ctr]);
Console.WriteLine();
}
}
// The example displays the following output:
// Household 1 has phone service: Yes
// Household 2 has phone service: No
// Household 3 has phone service: Yes
//
// Household 1 has cell phone service: Yes
// Household 2 has cell phone service: No
// Household 3 has cell phone service: Yes
//
// Household 1 has cell and land line service: Yes
// Household 2 has cell and land line service: No
// Household 3 has cell and land line service: No
//
// Household 1 has: LandLine, Cell, Internet
// Household 2 has: None
// Household 3 has: Cell, Internet
open System
[<Flags>]
type PhoneService =
| None = 0
| LandLine = 1
| Cell = 2
| Fax = 4
| Internet = 8
| Other = 16
// Define three variables representing the types of phone service
// in three households.
let household1 =
PhoneService.LandLine ||| PhoneService.Cell ||| PhoneService.Internet
let household2 =
PhoneService.None
let household3 =
PhoneService.Cell ||| PhoneService.Internet
// Store the variables in a list for ease of access.
let households =
[ household1; household2; household3 ]
// Which households have no service?
for i = 0 to households.Length - 1 do
printfn $"""Household {i + 1} has phone service: {if households[i] = PhoneService.None then "No" else "Yes"}"""
printfn ""
// Which households have cell phone service?
for i = 0 to households.Length - 1 do
printfn $"""Household {i + 1} has cell phone service: {if households[i] &&& PhoneService.Cell = PhoneService.Cell then "Yes" else "No"}"""
printfn ""
// Which households have cell phones and land lines?
let cellAndLand =
PhoneService.Cell ||| PhoneService.LandLine
for i = 0 to households.Length - 1 do
printfn $"""Household {i + 1} has cell and land line service: {if households[i] &&& cellAndLand = cellAndLand then "Yes" else "No"}"""
printfn ""
// List all types of service of each household?//
for i = 0 to households.Length - 1 do
printfn $"Household {i + 1} has: {households[i]:G}"
// The example displays the following output:
// Household 1 has phone service: Yes
// Household 2 has phone service: No
// Household 3 has phone service: Yes
//
// Household 1 has cell phone service: Yes
// Household 2 has cell phone service: No
// Household 3 has cell phone service: Yes
//
// Household 1 has cell and land line service: Yes
// Household 2 has cell and land line service: No
// Household 3 has cell and land line service: No
//
// Household 1 has: LandLine, Cell, Internet
// Household 2 has: None
// Household 3 has: Cell, Internet
<Flags()>
Public Enum PhoneService As Integer
None = 0
LandLine = 1
Cell = 2
Fax = 4
Internet = 8
Other = 16
End Enum
Module Example1
Public Sub Main()
' Define three variables representing the types of phone service
' in three households.
Dim household1 As PhoneService = PhoneService.LandLine Or
PhoneService.Cell Or
PhoneService.Internet
Dim household2 As PhoneService = PhoneService.None
Dim household3 As PhoneService = PhoneService.Cell Or
PhoneService.Internet
' Store the variables in an array for ease of access.
Dim households() As PhoneService = { household1, household2,
household3 }
' Which households have no service?
For ctr As Integer = 0 To households.Length - 1
Console.WriteLine("Household {0} has phone service: {1}",
ctr + 1,
If(households(ctr) = PhoneService.None,
"No", "Yes"))
Next
Console.WriteLine()
' Which households have cell phone service?
For ctr As Integer = 0 To households.Length - 1
Console.WriteLine("Household {0} has cell phone service: {1}",
ctr + 1,
If((households(ctr) And PhoneService.Cell) = PhoneService.Cell,
"Yes", "No"))
Next
Console.WriteLine()
' Which households have cell phones and land lines?
Dim cellAndLand As PhoneService = PhoneService.Cell Or PhoneService.LandLine
For ctr As Integer = 0 To households.Length - 1
Console.WriteLine("Household {0} has cell and land line service: {1}",
ctr + 1,
If((households(ctr) And cellAndLand) = cellAndLand,
"Yes", "No"))
Next
Console.WriteLine()
' List all types of service of each household?'
For ctr As Integer = 0 To households.Length - 1
Console.WriteLine("Household {0} has: {1:G}",
ctr + 1, households(ctr))
Next
Console.WriteLine()
End Sub
End Module
' The example displays the following output:
' Household 1 has phone service: Yes
' Household 2 has phone service: No
' Household 3 has phone service: Yes
'
' Household 1 has cell phone service: Yes
' Household 2 has cell phone service: No
' Household 3 has cell phone service: Yes
'
' Household 1 has cell and land line service: Yes
' Household 2 has cell and land line service: No
' Household 3 has cell and land line service: No
'
' Household 1 has: LandLine, Cell, Internet
' Household 2 has: None
' Household 3 has: Cell, Internet