枚举技巧~为枚举加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());

 

posted @ 2011-07-08 14:33  张占岭  阅读(1076)  评论(0编辑  收藏  举报