Dynamically add attribute "Go" to a class using TypeDescriptor

Source: Internet
Author: User

Source text: http://www.cnblogs.com/bicker/p/3326763.html

Add attribute to class dynamic has always been the problem I want to solve, from MSDN for a long time, to stack overflow read a lot of articles, is ultimately the answer.

First there's an explanation for this.

Attributes is 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 a instance of a attribute for a type and a change the properties if they ' re writable but that won ' t affect the attribute as it is applied to the type.

From this point of view, it is impossible to add attribute dynamically. Haha, the title pits it.

Okay, but I still found something. System.ComponentModel.TypeDescriptor, a class that claims to add attribute to classes and objects. There are methods in TypeDescriptor: AddAttributes, you can add attribute to the class. But there is only one problem, added to the attribute, can only be obtained through the TypeDescriptor.

 /* * now you need to add Simpleobject to Attribu Te */ Typedescriptor.addattributes (
       
        typeof (TargetObject), 
        new SimpleAttribute (new TargetObject ())); AttributeCollection collection = typedescriptor.getattributes (typeof (TargetObject)); SimpleAttribute attr = ((simpleattribute) collection[typeof if (attr! = null
       

Dynamically add attribute "Go" to a class using TypeDescriptor

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.