C#學習10

來源:互聯網
上載者:User

C#學習10:枚舉和結構體

枚舉類型是一組命名常量的集合,每種枚舉類型都有一種基本的類型,除char之外的所有整數類型都可作為枚舉類型的基本類型。

結構類型是一種複合資料型別,它包含常數,域,方法,屬性,索引器,操作符的巢狀型別,struct

類型適宜於點,矩形,顏色等輕量級的對象

定義一個枚舉類型,兩個結構體類型,實現一些基本的操作。

using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace com{    enum Season { Spring, Summer, Fall, Winter };    struct Time    {        public int hours, minutes, seconds;        public Time(int h, int m, int s)        {            hours = h;            minutes = m;            seconds = s;        }        public Time(int h, int m)        {            hours = h;            minutes = m;            seconds = 0;  //每個欄位都要賦值,這點和類不同        }        public int Hours()        {            return hours;        }        public int Minutes()        {            return minutes;        }        public int Seconds()        {            return seconds;        }    }    struct Date    {        public int year;        public Season s;        public Date(int a,Season b)        {            this.year=a;   // this是關鍵字,表示類的當前執行個體            this.s=b;        }    }    class Program    {        static void Main(string[] args)        {            Season s = Season.Spring;            Console.WriteLine(s);            Season i=0;            int j;            for (j = 0; j < 5; j++) //枚舉類型是從0開始的            {                Console.WriteLine(i);                i++;            }            Time t1= new Time();            Console.WriteLine(t1.Hours());//結構體預設的為0            Time t2 = new Time(10, 20, 30);            Console.WriteLine(t2.Hours());            Time t3 = new Time(10, 20);            Console.WriteLine(t3.Hours());            Date date=new Date(2012,0);            Console.WriteLine("年份是:{0},季節是: {1}",date.year,date.s);        }    }}

聯繫我們

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