Enum 读,和写 (相互转换)

本文详细介绍了C#中枚举(Enum)类型的使用方法,包括如何根据名称或值获取枚举类型、枚举值的遍历及组合使用等,并提供了丰富的示例代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

string sex = Enum.GetName(typeof(SexEnum), tempEmployee.Sex);

 

tempEmployee.Sex = (SexEnum)Enum.Parse(typeof(SexEnum),this.dpSex.SelectedValue);

 

 

 

[C#]Enum枚举类型使用总结
public enum Colors
{
  Red = 1,
  Green = 2,
  Blue = 4,
  Yellow = 8
};

The entries of the Colors Enum are:
Red
Green
Blue
Yellow


根据name获得Enum的类型:
Colors mycolor = (Colors)Enum.Parse(typeof(Colors),"red",true);
(int)mycolor1=1
mycolor1.GetTypeCode=Int32


根据value获得Enum的类型:
Colors mycolor = (Colors)Enum.Parse(typeof(Colors),"1",true);
mycolor2.ToString()=Red
mycolor2.GetTypeCode=Int32


遍历枚举内容
foreach(string s in Enum.GetNames(typeof(Colors)))
{
//to do
}


Colors myOrange = (Colors)Enum.Parse(typeof(Colors), "Red, Blue,Yellow");
The myOrange value has the combined entries of [myOrange.ToString()]=13


Colors myOrange2 = (Colors)Enum.Parse(typeof(Colors), "Red, Blue");
The myOrange2 value has the combined entries of [myOrange2.ToString()]=5
枚举方法 

  <1>获取枚举字符串

TimeOfDay time  =  TimeOfDay.Afternoon;

Console.WriteLine(time.ToString()); // 输出:Afternoon

  <2>Enum.Parse()方法。这个方法带 3 个参数,第一个参数是要使用的枚举类型。其语法是关键字 typeof 后跟放在括号中的枚举类名。 typeof 运算符将在第 5 章详细论述。第二个参数是要转换的字符串,第三个参数是一个 bool ,指定在进行转换时是否忽略大小写。最后,注意 Enum.Parse() 方法实际上返回一个对象引用—— 我们需要把这个字符串显式转换为需要的枚举类型 ( 这是一个取消装箱操作的例子 ) 。对于上面的代码,将返回 1 ,作为一个对象,对应于 TimeOfDay.Afternoon 的枚举值。在显式转换为 int 时,会再次生成 1。

TimeOfDay time2  =  (TimeOfDay) Enum.Parse( typeof (TimeOfDay),  " afternoon " ,  true );

Console.WriteLine(( int )time2); // 输出1

  <3>得到枚举的某一值对应的名称

lbOne.Text  =  Enum.GetName( typeof (TimeOfDay),  0 );
lbOne.Text  =  ((TimeOfDay) 0 ).ToString(); // 返回:Morning
两种方法都能实现,但是当其值越界(不是枚举所列出的值),就有一定的区别了。大家可以根据自己的需求不同,选择合适的方法。

lbCon.Text  =  ((TimeOfDay) 5 ).ToString();  // 返回:5,如果越界返回原值

this .lbGetName.Text  =  Enum.GetName( typeof (TimeOfDay),  5 );  // 返回:空字符串,如果越界返回空字符串
    <4>得到枚举的所有的值

foreach  ( int  i  in  Enum.GetValues( typeof (TimeOfDay)))
            lbValues.Text  +=  i.ToString();
    <5>枚举所有的名称

foreach ( string  temp  in  Enum.GetNames( typeof (TimeOfDay)))
            lbNames.Text += temp;

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值