posts - 609,  comments - 13,  views - 64万
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

代码:

复制代码
public class EnumberHelper  
    {  
        public static List<EnumberEntity> EnumToList<T>()  
        {  
            List<EnumberEntity> list = new List<EnumberEntity>();  
              
            foreach (var e in Enum.GetValues(typeof(T)))  
            {  
                EnumberEntity m = new EnumberEntity();  
                object[] objArr = e.GetType().GetField(e.ToString()).GetCustomAttributes(typeof(DescriptionAttribute), true);  
                if(objArr!=null && objArr.Length>0)  
                {  
                    DescriptionAttribute da = objArr[0] as DescriptionAttribute;  
                    m.Desction = da.Description;  
                }  
                m.EnumValue = Convert.ToInt32(e);  
                m.EnumName = e.ToString();  
                list.Add(m);  
            }  
            return list;  
        }  
    }  
  
    public class EnumberEntity  
    {  
        /// <summary>  
        /// 枚举的描述  
        /// </summary>  
        public string Desction { set; get; }  
  
        /// <summary>  
        /// 枚举名称  
        /// </summary>  
        public string EnumName { set; get; }  
  
        /// <summary>  
        /// 枚举对象的值  
        /// </summary>  
        public int EnumValue { set; get; }  
    } 
复制代码

枚举:

复制代码
public enum QxItem
    {
        [Description("查看")]
        Show = 0,
        [Description("新增")]
        Add = 1,
        [Description("编辑")]
        Edit = 2,
    }
复制代码

获取描述:

复制代码
 /// <summary>
        /// 获取枚举的描述
        /// </summary>
        /// <param name="enumValue"></param>
        /// <returns></returns>
        public static string GetEnumDescription(Enum enumValue)
        {
            string value = enumValue.ToString();
            FieldInfo field = enumValue.GetType().GetField(value);
            //获取描述属性
            object[] objs = field.GetCustomAttributes(typeof(DescriptionAttribute), false);
            //当描述属性没有时,直接返回名称
            if (objs.Length == 0)
            {
                return value;
            }
            DescriptionAttribute descriptionAttribute = (DescriptionAttribute)objs[0];
            return descriptionAttribute.Description;
        }
复制代码

 

另外一种:http://www.cnblogs.com/wenjian/archive/2009/06/19/1506550.html

 

posted on   邢帅杰  阅读(2179)  评论(0编辑  收藏  举报
编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】
点击右上角即可分享
微信分享提示