shensr

软件推动科技,科技改变世界!

博客园 首页 新随笔 联系 订阅 管理

我们经常会需要使用一个ComboBox来列出枚举类型所有可能的值,然后在根据用户所选择的值再反过来取枚举值。这时很多人会这样做----加的时候一条条加,取的时候再用一个switch一条条比较。

其实枚举类型的基类----Enum提供了一组静态方法来帮助我们简化这样的操作:

public static string[] GetNames(Type enumType);
public static Array GetValues(Type enumType);
public static object Parse(Type enumType, string value);
public static object Parse(Type enumType, string value, bool ignoreCase);

下面是一段测试代码:

Type t = typeof(System.DayOfWeek);
string[] names = Enum.GetNames(t);

foreach(string name in names)
{
    Console.WriteLine("Name is: {0}", name);
    System.DayOfWeek d = (System.DayOfWeek)Enum.Parse(t, name);
    Console.WriteLine("Parsing result is: {0}", d);
}

posted on 2004-06-22 12:46  shensr  阅读(1134)  评论(3编辑  收藏  举报