C#获取枚举描述的值

首先定义枚举

 工具类如下,通过扩展方法的方式实现:

复制代码
public static string GetDescription(this Enum value)
        {
            Type enumType = value.GetType();
            // 获取枚举常数名称。
            string name = Enum.GetName(enumType, value);
            if (name != null)
            {
                // 获取枚举字段。
                FieldInfo fieldInfo = enumType.GetField(name);
                if (fieldInfo != null)
                {
                    // 获取描述的属性。
                    DescriptionAttribute attr = Attribute.GetCustomAttribute(fieldInfo,
                        typeof(DescriptionAttribute), false) as DescriptionAttribute;
                    if (attr != null)
                    {
                        return attr.Description;
                    }
                }
            }
            return null;
        }
复制代码

使用:

 

 

 

出处:https://www.cnblogs.com/shenweif/p/16783500.html

posted on 2023-06-08 16:50  jack_Meng  阅读(651)  评论(0编辑  收藏  举报

导航