标签:style blog color io os 使用 ar 数据 div
基本语法与其他高级语言相通,
特殊用法1.
在枚举后使用冒号加上数据类型可以自定义枚举底层对应的数据类型,譬如:
1 enum CardDeckSetings : uint 2 { 3 SingleDeck =0x01, 4 LargePictures =0x02, 5 FancyNumbers =0x04, 6 Animation =0x08 7 }
2.使用位标识来进行识别:
声明一个包含有多个标志的对象:
CardDeckSetings ops = CardDeckSetings.SingleDeck | CardDeckSetings.FancyNumbers | CardDeckSetings.Animation;
此时可以通过进行与运算检测出对应位是否被设置
bool useFancyNumbers = (ops & CardDeckSetings.FancyNumbers) == CardDeckSetings.FancyNumbers;
注意此时需要在结构体前加入[Flags]标记:
1 [Flags] 2 enum CardDeckSetings : uint 3 { 4 SingleDeck =0x01, 5 LargePictures =0x02, 6 FancyNumbers =0x04, 7 Animation =0x08 8 }
设置Flags标志主要用于在编译器提取类似ops这样的变量时能够对已经进行或运算的变量进行分开处理(就是通知对ops输出的时候进行格式化的ToString()方法进行优化输出);
例如,不设置标志位情况下
1 namespace EnumTest 2 { 3 enum CardDeckSetings : uint 4 { 5 SingleDeck =0x01, 6 LargePictures =0x02, 7 FancyNumbers =0x04, 8 Animation =0x08 9 } 10 class Program 11 { 12 static void Main(string[] args) 13 { 14 CardDeckSetings ops = CardDeckSetings.SingleDeck | CardDeckSetings.FancyNumbers | CardDeckSetings.Animation; 15 16 Console.WriteLine("{0}",ops); 17 Console.ReadKey(); 18 } 19 } 20 }
输出是
13
,就是1+4+8的值;
设置后的输出就是:
SingleDeck,FancyNumbers,Animation
就是优化后的通过ToString值了
完整的使用方法:
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 7 namespace EnumTest 8 { 9 [Flags] 10 enum CardDeckSetings : uint 11 { 12 SingleDeck =0x01, 13 LargePictures =0x02, 14 FancyNumbers =0x04, 15 Animation =0x08 16 } 17 18 class MyClass 19 { 20 bool useSingleDeck = false; 21 bool useLargePictures = false; 22 bool useFancyNumbers = false; 23 bool useAnimation = false; 24 25 public void SetOptions(CardDeckSetings ops) 26 { 27 useSingleDeck = (ops & CardDeckSetings.SingleDeck) == CardDeckSetings.SingleDeck; 28 useLargePictures = (ops & CardDeckSetings.LargePictures) == CardDeckSetings.LargePictures; 29 useFancyNumbers = (ops & CardDeckSetings.FancyNumbers) == CardDeckSetings.FancyNumbers; 30 useAnimation = (ops & CardDeckSetings.Animation) == CardDeckSetings.Animation; 31 32 Console.WriteLine("ops={0}\n",ops); 33 } 34 35 public void PrintOptions() 36 { 37 Console.WriteLine("Option setting:"); 38 Console.WriteLine("CardDeckSetings.FancyNumbers={0}", useFancyNumbers); 39 Console.WriteLine("CardDeckSetings.LargePictures={0}", useLargePictures); 40 Console.WriteLine("CardDeckSetings.SingleDeck={0}", useSingleDeck); 41 Console.WriteLine("CardDeckSetings.Animation={0}", useAnimation); 42 } 43 } 44 class Program 45 { 46 static void Main(string[] args) 47 { 48 CardDeckSetings ops = CardDeckSetings.SingleDeck | CardDeckSetings.FancyNumbers | CardDeckSetings.Animation; 49 50 MyClass my = new MyClass(); 51 my.SetOptions(ops); 52 my.PrintOptions(); 53 Console.ReadKey(); 54 } 55 } 56 }
注意事项:
1.
可以将枚举看成常量,因此可以在没有枚举实例的情况下直接使用枚举名.枚举成员访问;
2.
不能比较不同类型的枚举成员;
标签:style blog color io os 使用 ar 数据 div
原文地址:http://www.cnblogs.com/lhyz/p/3978707.html