关键字enum用于声明枚举,枚举是一种值类型,由许多名字的常量(也叫枚举表)组成。例如
const int Monday=0;
const int Tuesday=1;
……
const Sunday=7;
可以用C#提供的枚举类型
enum Week
{ Monday,Tuesday, Wednesday, Thursday,Friday,Saturday,Sunday};
枚举中每一个常量都对应着一个数值,如果不特别设置,枚举从0开始,每个后续值都为前一个值加1。若有如下定义
enum Values
{
value1,
value2,
vlaue3
= 30 ,
value4
};
其中value1=0,value2=1,value3=30,value4=31;
需要注意的是在枚举类型和整型之间的转换需显示进行:
int a =(int) Week.Friday;
例如:
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);
}
}
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();
}
}
运行结果为