遍历枚举值

来源:互联网 发布:网络毛笔字 编辑:程序博客网 时间:2024/05/21 10:45

为了方便,我们通常将同类选项封装成枚举里,有时为了能让用户选择,需要将枚举里的值全部显示出来,我们可以通过Enum.GetValues(),方法实现,该方法的声明如下:

public static Array GetValues(Type enumType),Array:所有枚举值的集合,enumType:要获取的枚举类型
比如获取Colors里的所有颜色代码如下:
enum Colors { Red, Green, Blue, Yellow };
Colors []colors=Enum.GetValues(typeof(Colors)) as Colors[];//获取所有值得集合后便可通过下标来获取要选取的值
除了Enum.GetValues()方法Enum还提供Enum.GetNames()方法来获取枚举值字符串表示集合,其原型为:
public static string[] GetNames( Type enumType),string[]:为所有枚举值字符串集合,enumType:要获取的枚举类型
string []names=Enum.GetNames(typeof(Colors));//获取Colors里的枚举值字符串常量