C#3.0學習筆記(5)淺談枚舉

來源:互聯網
上載者:User

1, 什麼叫枚舉?

       答:枚舉是由程式員定義的類型,與類或結構一樣。

       註:1> 與結構一樣,枚舉是實值型別,因此直接儲存它們的資料,而不是分                           開儲存成引用和資料。枚舉儲存在棧中。

           2> 枚舉只有一種類型的成員:命名的整數值常量。

           3> 每個枚舉類型都有一個底層整數類型,預設為int。編譯器把第一個              成員賦值為0,並對每一個後續成員賦的值比前一個成員多1。

2, 枚舉在棧中排列的樣本?

       class Program

{

static voidMain(string[] args)

{

TrafficLight t1 = TrafficLight.Green;

TrafficLight t2 = TrafficLight.Yellow;

TrafficLight t3 = TrafficLight.Red;

Console.WriteLine("{0},{1}", t1,(int)t1);

Console.WriteLine("{0},{1}", t2, (int)t2);

Console.WriteLine("{0},{1}", t3, (int)t3);

Console.ReadKey();

}

}

enum TrafficLight

{

Green,

Yellow,

Red

}

       程式輸出的結果為:

       Green,0

       Yellow,1

       Red,2

3, 關於枚舉的補充?

       因為枚舉的成員是常量,即使在沒有該枚舉類型的變數時它們也可以訪問。使用枚舉    類型名跟著一個點和成員名。

       範例程式碼:

       class Program

{

static voidMain(string[] args)

{

Console.WriteLine("{0}", TrafficLight.Green);

Console.WriteLine("{0}", TrafficLight.Yellow);

Console.WriteLine("{0}", TrafficLight.Red);

Console.ReadKey();

}

}

enum TrafficLight

{

Green,

Yellow,

Red

}

       程式輸出結果:

       Green

       Yellow

       Red

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.