前言:
相信各位有碰到过与我类似的问题,当表中存一些状态的字段,无非以下几种形式1.直接写死 如: 正常:1,异常:2 ,还有一种则是写在字典中,再或者就是加在枚举上,前两者对于返回下拉数据源来说比较好处理,直接写死和查数据库,但都有各自的缺点,写死维护比较麻烦,查数据库也没必要,这个时候枚举就可以解决这个问题.
实现逻辑:
要返回一个List<StartStateEnum>
,其中包含枚举类型StartStateEnum
的所有字段值,你可以使用反射来实现。以下是一个示例代码,演示了如何将枚举类型中的字段值添加到集合并返回:
1 using System; 2 using System.Collections.Generic; 3 using System.ComponentModel; 4 using System.Reflection; 5 6 public class Program 7 { 8 public enum StartStateEnum 9 { 10 [Description("启动")] 11 Start = 0, 12 13 [Description("未启动")] 14 NotStart = 1 15 } 16 17 public static void Main(string[] args) 18 { 19 // 获取枚举字段值的集合 20 List<StartStateEnum> enumValues = GetEnumValues<StartStateEnum>(); 21 22 // 输出集合中的字段值 23 foreach (var value in enumValues) 24 { 25 Console.WriteLine(value); 26 } 27 } 28 29 public static List<T> GetEnumValues<T>() 30 { 31 // 获取枚举类型 32 Type enumType = typeof(T); 33 34 // 验证是否为枚举类型 35 if (!enumType.IsEnum) 36 { 37 throw new ArgumentException("The specified type is not an enum."); 38 } 39 40 // 获取枚举中的所有字段 41 FieldInfo[] fields = enumType.GetFields(BindingFlags.Public | BindingFlags.Static); 42 43 // 存储字段值的集合 44 List<T> enumValues = new List<T>(); 45 46 // 遍历字段并添加字段值到集合 47 foreach (var field in fields) 48 { 49 if (field.FieldType == enumType) 50 { 51 T value = (T)field.GetValue(null); 52 enumValues.Add(value); 53 } 54 } 55 56 return enumValues; 57 } 58 }
06-08 11:07