日期:2014-05-17 浏览次数:21168 次
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); } } }