C#将枚举转换为List集合

2022-09-19 15:32:14 浏览数 (1)

代码语言:javascript复制
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,

    }
}

调用代码:

代码语言:javascript复制
        [HttpGet("GetEnumItems")]
        public IActionResult GetEnumItems()
        {

            var enumItems = EnumItemHelper.GetEnumItems<OperateTypeCode>();

            return Ok(enumItems);
        }

返回结果如下:

代码语言:javascript复制
[
  {
    "code": "Call",
    "value": 0,
    "descprtion": "呼叫"
  },
  {
    "code": "Query",
    "value": 1,
    "descprtion": "查询"
  }
]

0 人点赞