您好,登錄后才能下訂單哦!
一、枚舉定義:
enum 關鍵字用于聲明枚舉,即一種由一組稱為枚舉數列表的命名常量組成的獨特類型。
二、枚舉規則:
1. 默認情況下,第一個枚舉數的值為 0,后面每個枚舉數的值依次遞增 1;也可強制元素序列從設定值而不是 0 開始
2. 準許使用的枚舉類型有 byte、sbyte、short、ushort、int、uint、long 或 ulong。
3. 枚舉類型作為位標志,應用 System.FlagsAttribute 特性,每個值都是 2 的若干次冪,可以對這些值執行 AND、OR、NOT 和 XOR 按位運算;避免標志指定零值。
三、枚舉例子:
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: //若要確定是否設置了特定標志,請使用按位 AND 運算
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\" 轉換為對象 Days2.Saturday ");
55: }
56:
57: }
58: }
59: }
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。