C# 通过反射获取类/方法的属性描述

  • A+
所属分类:.NET技术
摘要

    

    public class testDescrible     {          int _tt;         [Description("123")]         public int ttt         {             get             {                 return _tt;             }             set             {                 _tt = value;             }         }          [Description("测试1")]         public void TTT()         {          }          [Description("测试2")]         public void TTT(int A)         { }              } 

  

            testDescrible tst = new testDescrible();             Type t = tst.GetType();             //方法遍历             foreach (System.Reflection.MemberInfo p in t.GetMethods())             {                 object[] Attribute1 = p.GetCustomAttributes(true);                 //if (Attribute1.Length > 0)                 //{                 //    DescriptionAttribute myAttribute = (DescriptionAttribute)Attribute1[0];                 //    string aaa = myAttribute.Description;                 //}                  //object[] Attribute2 = p.GetCustomAttributes(typeof(QuickWebApiAttribute), false);             }             //属性遍历             foreach (System.Reflection.PropertyInfo pi in t.GetProperties())             {                                  AttributeCollection attributes = TypeDescriptor.GetProperties(t)[pi.Name].Attributes;                 DescriptionAttribute myAttribute = (DescriptionAttribute)attributes[typeof(DescriptionAttribute)];                 string describle = myAttribute.Description;             }