列挙テクニック~列挙にDescribe属性を加え、列挙要素の説明情報を出力する

4970 ワード

共通属性クラスを列挙します.
#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());