C# 通過反射獲取類/方法的屬性描述


    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();
            var attributesww = TypeDescriptor.GetProperties(t);

            //方法遍歷,遍歷實體類的相關public方法,不包含繼承的相關方法
            foreach (System.Reflection.MemberInfo p in t.GetMethods(System.Reflection.BindingFlags.Instance| System.Reflection.BindingFlags.Public| System.Reflection.BindingFlags.DeclaredOnly))
            {
                object[] Attribute1 = p.GetCustomAttributes(typeof(DescriptionAttribute), true);//只獲取DescriptionAttribute的特性
                object[] Attribute1123 = p.GetCustomAttributes(false);
                //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;
            }

  

  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM