Seconds to understand C # dynamically generate code from emit

Source: Internet
Author: User

You first need to declare an assembly name,

1//Specify a new assembly name2 var assemblyname = new AssemblyName ("Kitty");

Gets the assembly builder from the current application domain,

1//CREATE assembly builder2 var AssemblyBuilder = appdomain.currentdomain3   . DefineDynamicAssembly (AssemblyName, Assemblybuilderaccess.runandsave);

There are several dynamic assemblies that construct access restrictions:

    • Assemblybuilderaccess.run; Indicates that an assembly can be executed, but cannot be saved.
    • Assemblybuilderaccess.save; Indicates that the assembly can be saved, but cannot be executed.
    • Assemblybuilderaccess.runandsave; Indicates that the assembly can be saved and can be executed.
    • Assemblybuilderaccess.reflectiononly; Indicates that an assembly can only be used in a reflection context and cannot be executed.
    • Assemblybuilderaccess.runandcollect; Indicates that the assembly can be unloaded and that the memory is recycled.

Constructs a dynamic module in an assembly,

1//Create module builder2 var ModuleBuilder = assemblybuilder.definedynamicmodule ("Kittymodule", "Kitty.exe");

A module is a collection of code that can have multiple modules in one assembly. And in theory, each module can be implemented in a different programming language, such as C#/VB.
Constructs a type constructor,

1//Create type builder for a class2 var typeBuilder = Modulebuilder.definetype ("Hellokittyclass", Typeattributes.public) ;

Define a method through the type constructor, get the method constructor, get the Il generator of the method constructor, and define the method functionality by writing IL code.

1//Create Method Builder 2 var MethodBuilder = Typebuilder.definemethod (3   "Sayhellomethod", 4   MethodAttributes . Public | Methodattributes.static, 5   null, 6   null); 7   8//Then get the method Il generator 9 var il = methodbuilder.get ILGenerator ();  /Then create the method Function12 il. Emit (Opcodes.ldstr, "Hello, kitty!"); -IL. Emit (Opcodes.call,   typeof (Console). GetMethod ("WriteLine", new type[] {typeof (String)})); Emit (Opcodes.call, typeof (Console). GetMethod ("ReadLine")); Emit (Opcodes.pop); We just read something here, throw it.17 il. Emit (Opcodes.ret);

Create types,

1/Then create the whole class type2 var hellokittyclasstype = TypeBuilder.CreateType ();

If the current assembly is operational, set a program entry,

1//Set entry point to this assembly2 assemblybuilder.setentrypoint (Hellokittyclasstype.getmethod ("Sayhellomethod")) ;

Save the dynamically generated assembly to a disk file.

1//Save Assembly2 Assemblybuilder.save ("Kitty.exe");

At this point, the Kitty.exe is deserialized into code with the Anti-compilation tool,

1 using System; 2  3 public class Hellokittyclass 4 {5 public   static void Sayhellomethod () 6   {7     Console.WriteLine ("Hello , kitty! "); 8     Console.ReadLine (); 9   }10}

Run the results,

Full code
 1 using System; 2 using System.Reflection; 3 using System.Reflection.Emit; 4 5 Namespace Emitintroduction 6 {7 Class program 8 {9 static void Main (string[] args) Ten {one//speci       FY a new assembly name12 var assemblyname = new AssemblyName ("Kitty");//CREATE Assembly BUILDER15 var AssemblyBuilder = Appdomain.currentdomain16.       DefineDynamicAssembly (AssemblyName, Assemblybuilderaccess.runandsave);//Create Module BUILDER20       var ModuleBuilder = assemblybuilder.definedynamicmodule ("Kittymodule", "Kitty.exe"); 23 24 Create type builder for a class25 var typeBuilder = Modulebuilder.definetype ("Helloki Ttyclass ", typeattributes.public);//Create method builder30 var MethodBuilder = Typebuilder.definemetho D ("Sayhellomethod", Methodattributes.public |     methodattributes.static,33 null,34 null); 35 36  Then get the method il generator37 var il = methodbuilder.getilgenerator (); and then create the Metho d function40 IL. Emit (Opcodes.ldstr, "Hello, kitty!"); A. Il. Emit (Opcodes.call, typeof (Console). GetMethod ("WriteLine", new type[] {typeof (String)})); Emit (Opcodes.call, typeof (Console). GetMethod ("ReadLine")); Emit (Opcodes.pop); We just read something here, throw it.47 il. Emit (Opcodes.ret);/Then create the whole class type50 var hellokittyclasstype = TypeBuilder.CreateType (); entry//Set assembly53 Assemblybuilder.setentrypoint (hellokittyclasstype.g Etmethod ("Sayhellomethod")), and/or save assembly57 assemblybuilder.save ("Kitty.exe"); Teline ("Hi, Dennis, a Kitty assembly have been generated for you."); Console.ReadLine (); 62}63}64}

Download the full code

Further reading generating constructors and properties using emit

Seconds to understand C # dynamically generate code from emit

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.