C# Enum枚举类型使用总结

49 篇文章 0 订阅
39 篇文章 0 订阅

C# Enum枚举类型使用总结

工作学习 2011-04-14 13:37:20 阅读7 评论0   字号: 订阅

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;
 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值