根据值获取编号与根据编号获取值
internal class Program
{
static void Main(string[] args)
{
//根据编号获取值
Gender gender_1 = (Gender)1;
Gender gender_2 = (Gender)2;
Gender gender_3 = (Gender)3;
Console.WriteLine(gender_1);
Console.WriteLine(gender_2);
Console.WriteLine(gender_3);
//根据值获取编号
int num_male = (int)Enum.Parse(typeof(Gender), "Male");
int num_female = (int)Enum.Parse(typeof(Gender), "Female");
int num_other = (int)Enum.Parse(typeof(Gender), "Other");
Console.WriteLine(num_male);
Console.WriteLine(num_female);
Console.WriteLine(num_other);
}
}
//Enum类
enum Gender
{
Male = 1,
Female = 2,
Other = 3
}
运行效果
与Switch语句配合使用
//注意是Gender类型
Gender gender = Gender.Male;
switch (gender)
{
case Gender.Male:
Console.WriteLine("男性");
break;
case Gender.Female:
Console.WriteLine("女性");
break;
case Gender.Other:
Console.WriteLine("其他");
break;
default:
Console.WriteLine("无法识别");
break;
}
运行效果