一、定义一个类
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Reflection; namespace XXX.XXX.Utils { /// <summary> /// 备注特性 /// </summary> public class DescAttribute : Attribute { private string m_desc; public DescAttribute(string desc) { this.m_desc = desc; } /// <summary> /// 备注 /// </summary> public string Desc { get { return m_desc; } set { m_desc = value; } } /// <summary> /// 获取枚举的备注信息 /// </summary> /// <param name="val">枚举值</param> /// <returns></returns> public static string GetEnumDesc(Enum val) { Type type = val.GetType(); FieldInfo fd = type.GetField(val.ToString()); if (fd == null) return string.Empty; object[] attrs = fd.GetCustomAttributes(typeof(DescAttribute), false); string name = string.Empty; foreach (DescAttribute attr in attrs) { name = attr.Desc; } return name; } } /// <summary> /// 枚举扩展类 /// </summary> public static class EnumExtension { /// <summary> /// 获取枚举的备注信息 /// </summary> /// <param name="em"></param> /// <returns></returns> public static string GetDesc(this Enum em) { Type type = em.GetType(); FieldInfo fd = type.GetField(em.ToString()); if (fd == null) return string.Empty; object[] attrs = fd.GetCustomAttributes(typeof(DescAttribute), false); string name = string.Empty; foreach (DescAttribute attr in attrs) { name = attr.Desc; } return name; } } }
二、定义一个枚举,并引用如上命名空间
public enum EnumCalculationTag { [Desc("This is description")] A }
三、获取注解(需引用“一”中的命名空间)
EnumCalculationTag.A.GetDesc()