1、定义枚举类型 

public enum CommStatus
    {
        /// <summary>
        /// Udp类型
        /// </summary>
        [Description("Udp类型")] Udp = 0,

        /// <summary>
        /// Udp类型
        /// </summary>
        [Description("Udp广播类型")]
        Udpbroadcast = 1,
        /// <summary>
        /// Tcp服务端类型
        /// </summary>
        [Description("Tcp服务端类型")] TcpServer = 2,

        /// <summary>
        /// Tcp客户端类型
        /// </summary>
        [Description("Tcp客户端类型")] TcpClient = 3
    }

2、定义自定义属性类型

 public class DescriptionAttribute : Attribute
    {
        public DescriptionAttribute(string desc)
        {
            Description = desc;
        }

        public string Description { get; set; }
    }

3、通过反射获取枚举属性的自定义注释内容

public class EnumDescription
    {
        public static string GetEnumDescription<TEnum>(object value)
        {
            var enumType = typeof(TEnum);
            if (!enumType.IsEnum)
            {
                throw new ArgumentException($"enumItem req{value.ToString()}uires a Enum ");
            }
            var name = Enum.GetName(enumType, Convert.ToInt32(value));
            if (name == null)
                return "";
            var objs = enumType.GetField(name).GetCustomAttributes(typeof(DescriptionAttribute), false);
            var attr = objs[0] as DescriptionAttribute;
            if (objs.Length == 0)
            {
                return string.Empty;
            }
            else
            {
                return attr != null ? attr.Description : string.Empty;
            }
        }
    }

4、需要使用枚举的自定义注释的地方直接调用一下方法GetEnumDescription 给上枚举参数即可

 

相关文章:

  • 2021-11-30
  • 2021-12-29
  • 2022-12-23
  • 2022-12-23
  • 2021-08-30
  • 2021-11-02
猜你喜欢
  • 2021-08-06
  • 2021-06-18
  • 2021-09-27
  • 2022-01-14
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案