EnumDesc方法

using System;
using System.ComponentModel;

public string EnumDesc(Type type,int value)
        {
            string name = Enum.GetName(type, value);
            if (name == null)
            {
                return string.Empty;
            }
            FieldInfo field = type.GetField(name);
            DescriptionAttribute attribute = Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute)) as DescriptionAttribute;
            if (attribute == null )
            {
                return name;
            }
            return attribute == null ? string.Empty : attribute.Description;
        }

调用时:

public enum enum123
    {
        [Description("@a")]
        枚举a = 0,
        [Description("@b")]
        枚举b = 1,
        [Description("@c")]
        枚举c = 2
    }

EnumDesc(typeof(enum123), 0);

 

posted on 2023-05-06 10:12  一个小目标一次坑记录  阅读(60)  评论(0编辑  收藏  举报