通用枚举遍历 如果你确认你的枚举类型是 int32,可以使用以下方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 /// <summary> /// 将一个指定的枚举定义(Int)转换成集合对象. /// </summary> /// <typeparam name="T"></typeparam> /// <returns></returns> public static void ToList<T>() where T:Enum { Array datas = Enum.GetValues(typeof(T)); for (var i = 0; i < datas.Length; i++) { object value = datas.GetValue(i); Console.WriteLine("{0,-9} {1}", value + ":", (int)value); //需要注意的是这里的强转(int)value ,所以这里需要你事先确认枚举基础类型,如果是byte,此处会抛出异常 } }
有些时候你不能确认枚举的类型是int还是byte
demo示例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 enum BEnum : byte { A , B , C } var type = typeof(BEnum); FieldInfo[] fields = type.GetFields(); foreach (var field in fields) { if (field.FieldType!= type) { continue; } Console.WriteLine("{0,-9} {1}", field.Name + ":", field.GetRawConstantValue()); //field.GetRawConstantValue() 获取数值 //field.Name 获取枚举值名称 }
输出结果