[Enum] 列舉常用方法筆記
1: public enum LogType
2: {
3: [Description("save role")]
4: SaveRole,
5: [Description("delete role")]
6: DeleteRole
7: }
1: [TestMethod()]
2: public void EnumTest()
3: {
4: // 1. 列舉.ToString() 回傳命名的文字
5: Assert.AreEqual("SaveRole", LogDescFactory.LogType.SaveRole.ToString());
6:
7: // 2. 列舉.GetHashCode 被覆寫了, 回傳 0.
8: Assert.AreNotEqual(
9: "SaveRole".GetHashCode(),
10: LogDescFactory.LogType.SaveRole.GetHashCode());
11:
12: // 3. 列舉.轉型成integer時, 預設依序0,1,2 ...
13: Assert.AreEqual(0, (int)LogDescFactory.LogType.SaveRole);
14:
15: // 4. 列舉.不轉型時與integer不相等
16: Assert.AreNotEqual(0, LogDescFactory.LogType.SaveRole);
17:
18: // 5. 列舉.有順序的概念(as cast to integer)
19: Assert.IsTrue(
20: LogDescFactory.LogType.SaveRole
21: .CompareTo(LogDescFactory.LogType.DeleteRole) < 0);
22:
23: // 6. 列舉.可偵測是否有定義
24: Assert.IsTrue(Enum.IsDefined(typeof(LogDescFactory.LogType), 0));
25:
26: // 7. 列舉.由integer換回命名的文字
27: Assert.AreEqual("SaveRole", Enum.GetName(typeof(LogDescFactory.LogType), 0));
28:
29: // 8. 列舉.由integer換回物件, *註: 第二個參數是字串型態, 第三個參數是不區分大小寫
30: Assert.AreEqual(
31: LogDescFactory.LogType.SaveRole,
32: Enum.Parse(typeof(LogDescFactory.LogType), "0", true));
33:
34: // 9. 列舉.取得列舉描述
35: Assert.AreEqual(
36: "save role",
37: typeof(LogDescFactory.LogType)
38: .GetMember(LogDescFactory.LogType.SaveRole.ToString())[0]
39: .GetCustomAttributes(
40: typeof(System.ComponentModel.DescriptionAttribute), false)
41: .Select(x => (System.ComponentModel.DescriptionAttribute)x)
42: .FirstOrDefault()
43: .Description);
44: }