C#.NET MVC 枚举转dictionary

xiaoxiao2021-02-28  75

public enum StatuResult { [RemarkAttribute ("未审核")] WSH = 0, [RemarkAttribute("待审核")] DSH = 1, [RemarkAttribute("已审核")] YSH = 9 }         public static Dictionary<string, object> EnumToDic<T>(string keyDefault="", string valueDefault = "")         {             Dictionary<string, object> dicEnum = new Dictionary<string, object>();             Type enumType = typeof(T);             if (!enumType.IsEnum)             {                 return dicEnum;             }             if (!string.IsNullOrEmpty(keyDefault)) //判断是否添加默认选项               {                 dicEnum.Add(keyDefault, valueDefault);             }             string[] fieldstrs = Enum.GetNames(enumType); //获取枚举字段数组               foreach (var item in fieldstrs)             {                 string remark = string.Empty;                 var field = enumType.GetField(item);                 object[] arr = field.GetCustomAttributes(typeof(RemarkAttribute), true); //获取属性字段数组                   RemarkAttribute attr = (RemarkAttribute)arr.FirstOrDefault(a => a is RemarkAttribute);                 if (attr == null)                 {                     remark = field.Name;                 }                 else                 {                     remark = attr.Remark;                 }                 dicEnum.Add(remark, (int)Enum.Parse(enumType, item));  //不用枚举的value值作为字典key值的原因从枚举例子能看出来,其实这边应该判断他的值不存在,默认取字段名称               }             return dicEnum;         }
转载请注明原文地址: https://www.6miu.com/read-46046.html

最新回复(0)