一、枚舉定義:
創(chuàng)新互聯(lián)專注于冷水灘企業(yè)網(wǎng)站建設(shè),響應(yīng)式網(wǎng)站建設(shè),購(gòu)物商城網(wǎng)站建設(shè)。冷水灘網(wǎng)站建設(shè)公司,為冷水灘等地區(qū)提供建站服務(wù)。全流程按需規(guī)劃網(wǎng)站,專業(yè)設(shè)計(jì),全程項(xiàng)目跟蹤,創(chuàng)新互聯(lián)專業(yè)和態(tài)度為您提供的服務(wù)
enum 關(guān)鍵字用于聲明枚舉,即一種由一組稱為枚舉數(shù)列表的命名常量組成的獨(dú)特類型。
二、枚舉規(guī)則:
1. 默認(rèn)情況下,第一個(gè)枚舉數(shù)的值為 0,后面每個(gè)枚舉數(shù)的值依次遞增 1;也可強(qiáng)制元素序列從設(shè)定值而不是 0 開始
2. 準(zhǔn)許使用的枚舉類型有 byte、sbyte、short、ushort、int、uint、long 或 ulong。
3. 枚舉類型作為位標(biāo)志,應(yīng)用 System.FlagsAttribute 特性,每個(gè)值都是 2 的若干次冪,可以對(duì)這些值執(zhí)行 AND、OR、NOT 和 XOR 按位運(yùn)算;避免標(biāo)志指定零值。
三、枚舉例子:
1: using System;
2: using System.Collections.Generic;
3: using System.Linq;
4: using System.Text;
5:
6: namespace CSharp.Enum
7: {
8:
9: [Flags]
10: enum Days2
11: {
12: None = 0x0,
13: Sunday = 0x1,
14: Monday = 0x2,
15: Tuesday = 0x4,
16: Wednesday = 0x8,
17: Thursday = 0x10,
18: Friday = 0x20,
19: Saturday = 0x40
20: }
21:
22: class Program
23: {
24: static void Main(string[] args)
25: {
26: // Initialize with two flags using bitwise OR.
27: Days2 meetingDays = Days2.Tuesday | Days2.Thursday | Days2.Friday;
28: Console.WriteLine("Meeting days are {0}", meetingDays);
29:
30: // Remove a flag using bitwise XOR.
31: meetingDays = meetingDays ^ Days2.Tuesday;
32: Console.WriteLine("Meeting days are {0}", meetingDays);
33:
34: //若要確定是否設(shè)置了特定標(biāo)志,請(qǐng)使用按位 AND 運(yùn)算
35: bool test = (meetingDays & Days2.Thursday) == Days2.Thursday;
36: Console.WriteLine("Thursday {0} a meeting day.", test == true ? "is" : "is not");
37:
38: string saturday=System.Enum.GetName(typeof(Days2), 0x40);
39: Console.WriteLine("0x40 's Name is {0}",saturday);
40:
41: Console.WriteLine("The values of the Days2 Enum are:");
42: foreach (int i in System.Enum.GetValues(typeof(Days2)))
43: {
44: Console.WriteLine(i);
45: }
46:
47: Console.WriteLine("The names of the Days2 Enum are:");
48: foreach (string str in System.Enum.GetNames(typeof(Days2)))
49: Console.WriteLine(str);
50:
51: Days2 saturday2= (Days2)System.Enum.Parse(typeof(Days2), "Saturday");
52: if(System.Enum.IsDefined(typeof(Days2),saturday2))
53: {
54: Console.WriteLine(" \"Saturday\" 轉(zhuǎn)換為對(duì)象 Days2.Saturday ");
55: }
56:
57: }
58: }
59: }