C#将枚举转换为List集合
using System.ComponentModel; namespace ABenNetCore.FriendException.Helper { public class EnumItem { public string Code { get; set; } public int Value { get; set; } public string Descprtion { get; set; } } public class EnumItemHelper { public static List<EnumItem> GetEnumItems<T>() { var result = new List<EnumItem>(); Type enumType = typeof(T); if (!enumType.IsEnum) { return result; } string[] fieldstrs = Enum.GetNames(enumType); foreach (var item in fieldstrs) { string description = string.Empty; var field = enumType.GetField(item); object[] arr = field.GetCustomAttributes(typeof(DescriptionAttribute), true); //获取属性字段数组 if (arr != null && arr.Length > 0) { description = ((DescriptionAttribute)arr[0]).Description; //属性描述 } else { description = item; //描述不存在取字段名称 } result.Add(new EnumItem { Code = item, Value = (int)Enum.Parse(enumType, item), Descprtion = description, }); } return result; } } /// <summary> /// 操作类型编号 /// </summary> public enum OperateTypeCode { [Description("呼叫")] Call, [Description("查询")] Query, } }
调用代码:
[HttpGet("GetEnumItems")] public IActionResult GetEnumItems() { var enumItems = EnumItemHelper.GetEnumItems<OperateTypeCode>(); return Ok(enumItems); }
返回结果如下:
[ { "code": "Call", "value": 0, "descprtion": "呼叫" }, { "code": "Query", "value": 1, "descprtion": "查询" } ]
作者:阿笨
【官方QQ一群:跟着阿笨一起玩NET(已满)】:422315558
【官方QQ二群:跟着阿笨一起玩C#(已满)】:574187616
【官方QQ三群:跟着阿笨一起玩ASP.NET(已满)】:967920586
【官方QQ四群:Asp.Net Core跨平台技术开发(可加入)】:829227829
【官方QQ五群:.NET Core跨平台开发技术(可加入)】:647639415
【网易云课堂】:https://study.163.com/provider/2544628/index.htm?share=2&shareId=2544628
【腾讯课堂】:https://abennet.ke.qq.com
【51CTO学院】:https://edu.51cto.com/sd/66c64
【微信公众号】:微信搜索:跟着阿笨一起玩NET