zoukankan      html  css  js  c++  java
  • 枚举技巧~为枚举加Describe属性,输出枚举元素的说明信息

    这是枚举公用属性类:

    #region 枚举属性扩展类
    
        /// <summary>
    
        /// 枚举扩展方法
    
        /// </summary>
    
        public static class EnumExtensions
    
        {
    
            public static string GetDescription(this Enum obj)
    
            {
    
                return GetDescription(obj, false);
    
            }
    
            public static string GetDescription(this Enum obj, bool isTop)
    
            {
    
                if (obj == null)
    
                {
    
                    return string.Empty;
    
                }
    
                try
    
                {
    
                    Type _enumType = obj.GetType();
    
                    DescriptionAttribute dna = null;
    
                    if (isTop)
    
                    {
    
                        dna = (DescriptionAttribute)Attribute.GetCustomAttribute(_enumType, typeof(DescriptionAttribute));
    
                    }
    
                    else
    
                    {
    
                        FieldInfo fi = _enumType.GetField(Enum.GetName(_enumType, obj));
    
     
    
                        dna = (DescriptionAttribute)Attribute.GetCustomAttribute(
    
     
    
                           fi, typeof(DescriptionAttribute));
    
                    }
    
                    if (dna != null && string.IsNullOrEmpty(dna.Description) == false)
    
                        return dna.Description;
    
                }
    
                catch
    
                {
    
                    throw;
    
                }
    
                return obj.ToString();
    
     
    
            }
    
     
    
        }
    
        #endregion

    一个普通的枚举

     public enum OpreateType
    
        {
    
            [Description("添加")]
    
            Add = 0,
    
            Del = 1,
    
            Update = 2,
    
            Import = 3,
    
        }

    输出它指定枚举元素的描述信息

      Console.WriteLine(OpreateType.Add.GetDescription());
  • 相关阅读:
    优秀的 Java 项目,代码都是如何分层的?
    计算机应届生月薪大多是多少?
    零基础要怎么学JAVA?
    自学 Java 怎么入门?
    Java学习路线总结,已Get腾讯Offer
    java培训出来的如何找工作?
    离散数学学习笔记
    一些公式
    一个模拟
    秦皇岛wannafly[数论]学习笔记
  • 原文地址:https://www.cnblogs.com/lori/p/2100982.html
Copyright © 2011-2022 走看看