您的位置:首页 > 编程语言 > C#

c# 枚举实例

2009-11-05 09:17 218 查看
[分享][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;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: