我从这篇文章中提取了这个,这很有帮助。它展示了如何使用具有位移和按位信息的枚举。
http://www.codeducky.org/ins-outs-c-enums/
// this attribute isn't strictly necessary, but it provides
// useful metadata and greatly improves the ToString() representation
[Flags]
enum BookFlags
{
// most flags enums provide a named None or Default
// zero value to represent the empty set
Default = 0,
HardCover = 1,
InStock = HardCover << 1, // 2
HasEBook = InStock << 1, // 4
OnSale = HasEBook << 1, // 8
}
// we can create and test flag sets with bitwise operations
BookFlags flags = BookFlags.HardCover | BookFlags.InStock;
var text = flags.ToString(); // HardCover, InStock
var isInStock = (flags & BookFlags.InStock) == BookFlags.InStock; // true
// testing for a particular flag is also simplified by the HasFlag extension
var isInStock2 = flags.HasFlag(BookFlags.InStock); // true
编辑:如果你不能使用 HasFlag,你可能想要这样的东西。
// i redefined your enum a bit
public enum Buttons
{
// Default
Default = 0,
// Exit flags
Exit = 1,
Cancel = Exit << 1,
Abort = Cancel << 1,
Close = Abort << 1,
//Proced flags
Accept = Close << 1,
Ok = Accept << 1,
Submit = Ok << 1,
//Question flags
No = Submit << 1,
Yes = No << 1,
//Save and load
Save = Yes << 1,
SaveAll = Save << 1,
SaveNew = SaveAll << 1,
Open = SaveNew << 1,
Load = Open << 1
}
然后你可以...
// here's checking a selection of buttons against the complete enum universe of values
var lastButton = Convert.ToInt32(Enum.GetValues(typeof(Buttons)).Cast<Buttons>().Max());
int enumCheck;
Buttons flags = Buttons.Ok | Buttons.SaveNew | Buttons.Load | Buttons.No | Buttons.Submit | Buttons.Exit;
for (int i = 0; Math.Pow(2, i) <= lastButton; i++)
{
enumCheck = (int)Math.Pow(2, i);
if ((flags & (Buttons)enumCheck) == (Buttons)enumCheck)
{
Debug.WriteLine(Enum.GetName(typeof(Buttons), enumCheck));
}
}
产生输出(注意顺序):
Exit
Ok
Submit
No
SaveNew
Load