CLR via C# 笔记 -- 枚举(15)

1. 枚举继承System.Enum,后者继承 System.ValueType,所以枚举是值类型。

2. 枚举不能定义任何方法、属性和事件,不过可以定义扩展方法

3. ToString()方法

Color c = Color.Blue;
Console.WriteLine(c);                   // "Blue"
Console.WriteLine(c.ToString());        // "Blue"
Console.WriteLine(c.ToString("G"));     // "Blue"
Console.WriteLine(c.ToString("D"));     // "3"
Console.WriteLine(c.ToString("X"));     // 03

4. 获取所有的值

Color[] colors = (Color[])Enum.GetValues(typeof(Color));

5. IsDefined()方法很方便,但必须谨慎使用。1)总是执行区分大小写的查找;2)内部使用了反射,速度不快。

6. 标志位 [Flags]

internal enum Actions 
{
    None = 0,
    Read = 0x0001,
    Write = 0x0002,
    ReadWrite = Actions.Read | Actions.Write,
    Delete = 0x0004,
    Query = 0x0008,
    Sync = 0x0010,
    All = Actions.None | Actions.Read | Actions.Write | Actions.ReadWrite | Actions.Delete | Actions.Query | Actions.Sync 
}

Actions actions = Actions.Read | Actions.Delete;
Console.WriteLine(actions.ToString("F"));  // Read, Delete

7. Parse() 和 TryParse() 会自动删除头尾空白字符;字符串会被分解为一组以逗号分隔符的token,但IsDefined() 不会有这样的操作

原文地址:https://www.cnblogs.com/Cxiaoao/p/14839144.html