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": "查询"
  }
]

 

posted @ 2022-07-29 21:58  跟着阿笨一起玩.NET  阅读(1288)  评论(0编辑  收藏  举报