zoukankan      html  css  js  c++  java
  • 自定义枚举类型的注释属性用于UI的显示

    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 给上枚举参数即可

  • 相关阅读:
    一些必不可少的Sublime Text 2插件
    sublime text 使用小技巧
    Azure Queue 和 Service Bus Queue的比较
    怎么使用Windows Azure Queue Storage 服务
    配置 SharePoint 2010 使用本机默认 SQL Server 实例 Pan
    将两个字符串中相同的地方str2无重复的输出
    javascript笔记
    C#中怎样使控件随着窗体一起变化大小(拷来学习)
    在pictureBox中画方格矩阵地图,方法比较笨,有好方法望指导
    通过一个小推理写出的程序,结果出乎意料……有哪位知道为什么吗 已解决
  • 原文地址:https://www.cnblogs.com/Ray898/p/4924145.html
Copyright © 2011-2022 走看看