- 本文汇总了一些有关C#枚举的问答。本文是第三部分,汇总了一些有关枚举的使用情景以及一些限制。
之前介绍了C#枚举的基础与赋值相关的知识,本文继续介绍有关C#枚举的一些问答。
Q:我定义了一个这样的枚举:
- // Code #20
- public enum FontStyle
- {
- Bold,
- Italic,
- Regular,
- Strikethrough,
- Underline
- }
我用它来指定字体的风格,但我遇到了麻烦。你知道,字体可以同时拥有枚举里面所列举的一种或者多种风格,那么,我如何为字体同时指定多种风格呢?
A:这个时候你就需要位枚举(Bit Flags),把Code #20修改一下:
- // Code #21
- // I am using the FlagsAttribute to identify a bit flags.
- [Flags]
- public enum FontStyle
- {
- Bold = 0x0001,
- Italic = 0x0002,
- Regular = 0x0004,
- Strikethrough = 0x0010,
- Underline = 0x0020
- }
现在,你可以通过按位或运算来为字体指定多种风格了:
- // Code #22
- // See Code #21 for FontStyle.
- Font f = new Font(
- FontFamily.GenericSansSerif,
- 12.0F,
- FontStyle.Italic | FontStyle.Underline
- );
--------------------------------------------------------------------------------
Q:位枚举同样存在类似于Code #15的恶作剧吧?
A:是的,例如:
- // Code #23
- // See Code #21 for FontStyle.
- class Program
- {
- static void Main()
- {
- Bar(FontStyle.Regular | (FontStyle)0x0400);
- }
- static void Bar(FontStyle fs)
- {
- // Code here
- }
- }
--------------------------------------------------------------------------------
Q:那么,System.Enum.IsDefine方法是否还能应对呢?
A:不能。位枚举成员并不具备排他性,多个成员可以通过按位或运算组合起来。而System.Enum.IsDefine方法只能判断枚举变量的值是否为某一已定义的枚举成员。请看如下代码:
- // Code #24
- // See Code #21 for FontStyle.
- FontStyle fs1 = FontStyle.Bold | FontStyle.Italic | FontStyle.Underline;
- Console.WriteLine(Enum.IsDefine(typeof(FontStyle), fs1));
- FontStyle fs2 = FontStyle.Regular | (FontStyle)0x0400;
- Console.WriteLine(Enum.IsDefine(typeof(FontStyle), fs2));
- // Output:
- // false
- // false
我们对代码的输出毫无疑问,因为fs1和fs2都不是一个单独的枚举成员。但这不是我们所追求的答案,我们希望区别对待fs1和fs2,至少我们不希望fs2中的捣蛋家伙——(FontStyle)0x0400——在我们的程序中搞破坏!
--------------------------------------------------------------------------------
Q:那么,我们是否有办法隔离这些捣蛋鬼呢?
A:Of course!我们同样可以使用条件判断语句来处理,但做法将与Code #17和Code #18有所不同。现在我们把Code #23改进如下:
- // Code #25
- // See Code #21 for FontStyle.
- class Program
- {
- static void Main()
- {
- Bar(FontStyle.Regular | (FontStyle)0x0400);
- }