C#枚舉類型的使用樣本

來源:互聯網
上載者:User
 

C#枚舉類型的使用樣本 介紹
枚舉是一個指定的常數,其基礎類型可以是除 Char 外的任何整型。
如果沒有顯式聲明基礎類型,則使用 Int32。
程式設計語言通常提供文法來聲明由一組已命名的常數和它們的值組成的枚舉。
定義
預設基數從O開始,也可指定數值。
enum Days { Saturday=1, Sunday, Monday, Tuesday, Wednesday, Thursday, Friday };
enum Colors { Red = 1, Green = 2, Blue = 4, Yellow = 8 };

使用
Colors myColors = Colors.Red;
string strColor=myColors.tostring();
int    IntColor=(int)myColors ; 
位或
Colors myColors = Colors.Red | Colors.Blue | Colors.Yellow;
位與
Colors myColors = Colors.Red & Colors.Blue & Colors.Yellow;
遍曆 
foreach (string s in Enum.GetNames(typeof(Days)))
  Response.Write(s + "--" + Enum.Parse(typeof(Days), s).ToString());
轉換
Colors mc=Colors Enum.Parse(typeof(Colors ), "red"); 
 if (System.Enum.IsDefined(typeof(Days), "Monday"))
   Days ds= (Days)Enum.Parse(typeof(Days), "Monday");


執行個體二:
    public enum NoticeType
    {
        Notice = 'A',
        LabRule = 'H',
        HotInformation = 'N',
        Column = 'C',
        All = '1',
        Null = '0'
    }
     //建立枚舉類型
        NoticeType noticeType1 = NoticeType.Column;

        //把枚舉類型轉換為string d="Column"
        string d = noticeType1.ToString();

        //取得枚舉類型的基數 dd='C'
        char dd = (char)noticeType1;

        //通過基數取得對應的枚舉類型 noticeType2 = NoticeType.Notice
        //(NoticeType)'A';  兩種方式都可以
        NoticeType noticeType2 = (NoticeType)Char.Parse("A"); 

    //通過名稱取得枚舉類型 noticeType3 = NoticeType.Notice
        NoticeType noticeType3 = (NoticeType)Enum.Parse(typeof(NoticeType), "Notice");
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.