位枚举(Bit Flags)
场景:如字体,一个字体可以同时拥有枚举里面所列举的一种或者多种风格,这时就需要位枚举
定义:
[Flags]
public enum FontStyle
{
Bold = 0x0001,
Italic = 0x0002,
Regular = 0x0004,
Strikethrough = 0x0010,
Underline = 0x0020
}
public enum FontStyle
{
Bold = 0x0001,
Italic = 0x0002,
Regular = 0x0004,
Strikethrough = 0x0010,
Underline = 0x0020
}
Example: 可以通过按位或运算来为字体指定多种风格,如下
Font f = new Font(
FontFamily.GenericSansSerif,
12.0F,
FontStyle.Italic | FontStyle.Underline
);
FontFamily.GenericSansSerif,
12.0F,
FontStyle.Italic | FontStyle.Underline
);
枚举变量与某一特定的位枚举成员进行按位与运算,若结果不为0则表明枚举变量中包含着该位枚举成员
static void Bar(FontStyle fs)
{
if ((fs & FontStyle.Bold) != 0)
{
// Do something associated with bold
}
if ((fs & FontStyle.Italic) != 0)
{
// Do something associated with italic
}
// Other conditional code continues here
}
{
if ((fs & FontStyle.Bold) != 0)
{
// Do something associated with bold
}
if ((fs & FontStyle.Italic) != 0)
{
// Do something associated with italic
}
// Other conditional code continues here
}