/// <summary> /// 将枚举对象转化为 /// </summary> /// <param name="type"></param> /// <returns></returns> public static string EnumToJson(this Type type) { if (!type.IsEnum) throw new InvalidOperationException("enum expected"); var enumValues =Enum.GetValues(type); Dictionary<int, string> result = new Dictionary<int, string>(); foreach (var item in enumValues) { //FieldInfo fieldInfo = type.GetField(item); string name = Enum.GetName(type, item); if (name != null) { // 获取枚举字段。 FieldInfo fieldInfo = type.GetField(name); if (fieldInfo != null) { // 获取描述的属性。 DescriptionAttribute attr = Attribute.GetCustomAttribute(fieldInfo, typeof(DescriptionAttribute), false) as DescriptionAttribute; if (attr != null) { result.Add((int)item,attr.Description); } } } } return JsonConvert.SerializeObject(result); }
直接写在枚举内