使用TypeDescriptor給類動態添加Attribute


給類動態添加Attribute一直是我想要解決的問題,從msdn里找了很久,到Stack Overflow看了不少文章,算是最終有了答案。

先是有這樣的一段解釋

Attributes are static metadata. Assemblies, modules, types, members, parameters, and return values aren't first-class objects in C# (e.g., the System.Type class is merely a reflected representation of a type). You can get an instance of an attribute for a type and change the properties if they're writable but that won't affect the attribute as it is applied to the type.

從這里看,想要實現動態添加Attribute就是不可能做到的。哈哈,被標題坑了吧。

好吧,但是我還是找到了一個東西System.ComponentModel.TypeDescriptor,這個號稱可以添加Attribute到類、對象中去的類。TypeDescriptor里有方法:AddAttributes,可以把Attribute添加到類上。但是只有一個問題,添加上去的Attribute,只能通過TypeDescriptor來取到。

           /*
             *    現在需要給simpleObject添加attribute
             */
            TypeDescriptor.AddAttributes(typeof(targetObject), new simpleAttribute(new targetObject()));
            AttributeCollection collection = TypeDescriptor.GetAttributes(typeof(targetObject));
            simpleAttribute attr = ((simpleAttribute)collection[typeof(simpleAttribute)]);
            if (attr != null)
            {
                MessageBox.Show(attr.ToString());
            }   

 


免責聲明!

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



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