二十、枚舉類型

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace _20.枚舉類型
{
    enum orientation : byte
    {
        north = 1,
        south = 2,
        east = 3,
        west = 4
    }
    
    class Program
    {
        static void Main(string[] args)
        {
            /**
             * 枚舉類型:
             * 使用enum關鍵字定義枚舉類型。
             * 其定義語法:
             *  enum <typeName> [: <underlyingType>]
             *  {
             *      <value1>,
             *      <value2>,
             *      <value3>,
             *      ...
             *      <valueN>
             *  }
             *  
             * 定義枚舉變量:
             *  <typeName> <varName>;
             *  
             * 引用枚舉變量:
             *  <varName> = <typeName>.<value>;
             *  
             * 解析說明:
             * 1. 枚舉使用一個基本類型來存儲。
             * 2. 枚舉類型可以提取每個值都存儲爲該基本類型的一個值,默認情況下該類型爲int。
             * 3. <underlyingType>用來指定枚舉值類型。
             * 4. 枚舉的基本類型:byte,sbyte,short,ushort,int,uint,long,ulong。
             * 5. 在默認情況下,每個值都會根據定義的順序(從0開始),自動賦值給對應的基本類型值。
             * 6. 使用=號運算符,指定每個枚舉的實際值,可以多個枚舉指定相同的值。
             * 7. 以循環方式指定枚舉值會出現錯誤。
             *    例如:
             *    enum <typeName> : <underlyingType>
             *    {
             *      <value1> = <value2>,
             *      <value2> = <value1>,
             *    }
             * 
             */
             
            byte directionByte;
            string directionString
            ;
            orientation myDirection = orientation.north;
            Console.WriteLine("myDirection = {0}", myDirection);
            
            directionByte = (byte)myDirection;
            directionString = Convert.ToString(myDirection);
            
            Console.WriteLine("byte equivalent = {0}", directionByte);
            Console.WriteLine("string equivalent = {0}", directionString);
            Console.WriteLine("string equivalent = {0}", myDirection.ToString());
            
            // 以下方法作用:把string類型轉換爲枚舉值。
            // (enumerationType)Enum.Parse(typeof(enumerationType), enumerationValueString);
            // enumerationValueString參數是區分大小寫的。
            // typeof運算符是得到操作數的類型。
            
            string myString = "west";
            
            orientation direction = (orientation)Enum.Parse(typeof(orientation), myString);
            Console.WriteLine("direction = {0}", (byte)direction);
            
            Console.ReadKey();
        }
    }
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章