使用TypeDescriptor給類動態添加Attribute【轉】

來源:互聯網
上載者:User

標籤:

源文 : http://www.cnblogs.com/bicker/p/3326763.html

給類動態添加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()); } 

使用TypeDescriptor給類動態添加Attribute【轉】

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.