C#枚举型ENum

关键记号: ENum.GetValues, ENum.GetNames
 
写个小东西,刚好用到枚举类型,需要显示在DropDownList控件中。尝试了下,用如下方法可以实现。 

比如定义了一个错误的枚举类型

   

1 public enum eErrorDetailCode : int
2         {
3             登陆成功 = 0,
4             登出 = 1,
5             应用错误 = 2,
6             成功 = 16,
7             失败 = 17
8         }

 

需要引用

using System;

 然后在循环中,遍历枚举对象的所有元素

 

1 foreach (int  myCode in Enum.GetValues(typeof(eErrorDetailCode)))
2             {
3                 string strName =Enum.GetName(typeof(eErrorDetailCode), myCode);//获取名称
4                 string strVaule = myCode.ToString();//获取值
5                 ListItem myLi = new ListItem(strName,strVaule);
6                 ddlType.Items.Add(myLi);//添加到DropDownList控件
7             }
 

using System;

public class EnumTest {
enum Days { Saturday, Sunday, Monday, Tuesday, Wednesday, Thursday, Friday };
enum BoilingPoints { Celcius = 100, Fahrenheit = 212 };
[FlagsAttribute]
enum Colors { Red = 1, Green = 2, Blue = 4, Yellow = 8 };

public static void Main() {

Type weekdays = typeof(Days);
Type boiling = typeof(BoilingPoints);

Console.WriteLine("The days of the week, and their corresponding values in the Days Enum are:");

foreach ( string s in Enum.GetNames(weekdays) )
Console.WriteLine( "{0,-11}= {1}", s, Enum.Format( weekdays, Enum.Parse(weekdays, s), "d"));

Console.WriteLine();
Console.WriteLine("Enums can also be created which have values that represent some meaningful amount.");
Console.WriteLine("The BoilingPoints Enum defines the following items, and corresponding values:");

foreach ( string s in Enum.GetNames(boiling) )
Console.WriteLine( "{0,-11}= {1}", s, Enum.Format(boiling, Enum.Parse(boiling, s), "d"));

Colors myColors = Colors.Red | Colors.Blue | Colors.Yellow;
Console.WriteLine();
Console.WriteLine("myColors holds a combination of colors. Namely: {0}", myColors);
}
}

posted @ 2012-08-19 19:47  C#老头子  Views(401)  Comments(0Edit  收藏  举报