是为了限定取值范围的 .比如一个变量是整型,但是可接受范围只有0-6,如果传七就不对了. public enum WeekDay:int { sonday = 0, monday = 1, tuesday = 2, ..... }
C#枚举,枚举是一种值类型,由许多名字的常量(也叫枚举表)组成。例如
- const int Monday=0;
- const int Tuesday=1;
- ……
- const Sunday=7;
可以用C#枚举类型
- enum Week
- { Monday,Tuesday, Wednesday,
- Thursday,Friday,Saturday,Sunday};
C#枚举中每一个常量都对应着一个数值,如果不特别设置,枚举从0开始,每个后续值都为前一个值加1。若有如下定义
- enum Values
- {
- value1,
- value2,
- vlaue3=30,
- value4
- };
其中value1=0,value2=1,value3=30,value4=31;
需要注意的是在C#枚举类型和整型之间的转换需显示进行:
- int a =(int) Week.Friday;
C#枚举类型示例:
- public class food
- {
- public enum foodType
- { Pizza=1,Pasta,Spaghetti}
- public void GetFoodOrder(string Custname,
- foodType order)
- {
- Console.WriteLine("the dinner of customer
- {0} is {1}",Custname,order);
- }
- } //C#枚举类型
- class Program
- {
- static void Main(string args)
- {
- food myfood = new food();
- myfood.GetFoodOrder("Scoopy",(food.foodType.Pizza));
- Console.WriteLine("您享用的是本店的第"+
- (int)food.foodType.Pizza+"种主食");
- Console.ReadLine();
- }
- }
C#枚举类型实例运行结果为
C#枚举类型实例的详细讲解就到这里,希望对你了解和学习C#枚举类型有所帮助。