首页 > 代码库 > 一个读取C#特性Description方法(zhuan)

一个读取C#特性Description方法(zhuan)

技术分享
class Program
    {
        static void Main(string[] args)
        {
          string str=  DB.write.ToDescription();
          Console.WriteLine(str);
          Console.ReadKey();
        }


     
    }


 
       public enum  DB{
           [Description("")]
          write=1,
           [Description("")]
           read=2
       }

       public static class MyException
       {
           /// <summary>
           /// 获取枚举类型的描述
           /// </summary>
           /// <param name="enumeration"></param>
           /// <returns></returns>
           public static string ToDescription(this Enum enumeration)
           {
               Type type = enumeration.GetType();
               MemberInfo[] memInfo = type.GetMember(enumeration.ToString());
               if (null != memInfo && memInfo.Length > 0)
               {
                   object[] attrs = memInfo[0].GetCustomAttributes(typeof(DescriptionAttribute), false);
                   if (null != attrs && attrs.Length > 0)
                       return ((DescriptionAttribute)attrs[0]).Description;
               }
               return enumeration.ToString();
           }
          
       }
View Code

 

一个读取C#特性Description方法(zhuan)