Emit: dynamically add attribute to a Type

Source: Internet
Author: User

The following Code is compiled from the official document of sl4, which has been annotated in detail. I believe everyone can understand it:

Using system; using system. reflection; using system. reflection. emit; using system. threading; namespace customattributebuildersample {public class democlass {static void main (string [] ARGs) {// obtain the new type mytype = buildtypewithcustomattributesonmethod (); // create a mytype Instance Object myinstance = activator. createinstance (mytype); // obtain all attribute objects applied on mytype [] customattrs = mytype. getcustomattributes (true); console. writeline ("custom attributes for Type 'mytype':" + "\ n"); object attrval = NULL; foreach (Object customattr in customattrs) {// obtain the Creator attribute value attrval = typeof (classcreatorattribute) in classcreatorattribute ). invokemember ("creator", bindingflags. getproperty, null, customattr, new object [] {}); console. writeline (string. format ("-- attribute: [{0 }=\" {1} \ "]", customattr, attrval) + "\ n");} console. writeline ("custom attributes for method 'helloworld () 'in 'mytype':" + "\ n"); // obtain all attributes customattrs = mytype in the helloworld method of mytype. getmember ("helloworld") [0]. getcustomattributes (true); foreach (Object customattr in customattrs) {// gets the dateupdated attribute value of datelastupdatedattribute attrval = typeof (datelastupdatedattrites ). invokemember ("dateupdated", bindingflags. getproperty, null, customattr, new object [] {}); console. writeline (string. format ("-- attribute: [{0 }=\" {1} \ "]", customattr, attrval) + "\ n");} console. writeline ("---" + "\ n"); // dynamically call the helloworld method console in the mytype instance. writeline (mytype. invokemember ("helloworld", bindingflags. invokemethod, null, myinstance, new object [] {}) + "\ n"); console. readkey ();} /// <summary> /// create a classcreatorattribute and datelastupdatedattribute type. /// </Summary> /// <returns> </returns> Public static type buildtypewithcustomattributesonmethod () {appdomain currentdomain = thread. getdomain (); assemblyname myasmname = new assemblyname (); myasmname. name = "myassembly"; // create a dynamic Program Set assemblybuilder myasmbuilder = currentdomain. definedynamicassembly (myasmname, assemblybuilderaccess. run); // dynamically create a module modulebuilder mymodbuilder = myasmbuilder. definedynamicmodule ("mymodule"); // dynamically create a type: mytype typebuilder mytypebuilder = mymodbuilder. definetype ("mytype", typeattributes. public); // define the constructor parameter type [] ctorparams = new type [] {typeof (string)}; // obtain constructorinfo classctorinfo = Typeof (classcreatorattribute ). getconstructor (ctorparams); // dynamically create classcreatorattribute customattributebuilder mycabuilder = new customattributebuilder (classctorinfo, new object [] {"Joe programmer "}); // Add the attribute dynamically created above to the (dynamically created) type mytype mytypebuilder. setcustomattrider (mycabuilder); // dynamically create a non-return value, no parameter, public method helloworld methodbuilder mymethodbuilder = mytypebuilder. definemethod ("helloworld", methoda Ttributes. public, null, new type [] {}); ctorparams = new type [] {typeof (string)}; // obtain the information of the constructor of datelastupdatedattribute classctorinfo = typeof (datelastupdatedattribute ). getconstructor (ctorparams); // dynamically create datelastupdatedattribute matmattributebuilder mycabuilder2 = new customattributebuilder (classctorinfo, new object [] {datetime. now. tostring ()}); // attaches the attribute dynamically created above to the (dynamically created) method helloworld mymet Hodbuilder. setcustomattrieline (mycabuilder2); ilgenerator myil = mymethodbuilder. getilgenerator (); myil. emitwriteline ("Hello, world! "); // In the helloworld method, creating a row is equivalent to console. Write (" Hello, world! "); Code myil. emit (Opcodes. RET); // Return Statement of the helloworld method return mytypebuilder. createtype () ;}/// <summary> // create a custom attribute, apply it to the dynamically created "type" later. // </Summary> public class classcreatorattribute: attribute {private string creator; Public String creator {get {return creator ;}} public classcreatorattribute (string name) {This. creator = Name ;}/// <summary> // create a custom attribute, apply it to the dynamically created "method" Later // </Summary> public class datelastupdatedattribute: attribute {private string dateupdated; Public String dateupdated {get {return dateupdated ;}} public datelastupdatedattridate (string thedate) {This. dateupdated = thedate ;}}}

Output result:

Custom Attributes for Type 'mytype ':

-- Attribute: [customattributebuildersample. classcreatorattribute = "Joe program mer"]

Custom Attributes for method 'helloworld () 'in 'mytype ':

-- Attribute: [customattributebuildersample. datelastupdatedattribute = "2011/11/13 21:46:31"]

---

Hello, world!

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.