Second C # dynamically generate code through emit

Source: Internet
Author: User

First, declareProgramSet Name,

 
//Specify a new Assembly nameVaRAssemblyname =NewAssemblyname ("Kitty");

Obtains the Assembly constructor from the current application domain,

 
//Create Assembly BuilderVaRAssemblybuilder =Appdomain. currentdomain. definedynamicassembly (assemblyname, assemblybuilderaccess. runandsave );

There are several types of dynamic assembly construction access restrictions:

    • Assemblybuilderaccess. Run; indicates that the 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 executed.
    • Assemblybuilderaccess. reflectiononly; indicates that an assembly can only be used to reflect the context and cannot be executed.
    • Assemblybuilderaccess. runandcollect; indicates that the Assembly can be detached and the memory will be recycled.

Construct dynamic modules in a program set,

 
//Create module BuilderVaRModulebuilder = assemblybuilder. definedynamicmodule ("Kittymodule","Kitty.exe");

Module isCodeA set of programs can have multiple modules. In theory, each module can use differentProgramming LanguageImplementation, such as C #/VB.
Construct a Type constructor,

 
//Create type builder for a classVaRTypebuilder = modulebuilder. definetype ("Hellokittyclass", Typeattributes. Public );

Define a method through the Type constructor, obtain the method constructor, obtain the Il generator of the method constructor, and define the method function by writing the Il code.

       //  Create method Builder        VaR Methodbuilder = Typebuilder. definemethod (  " Sayhellomethod  "  , Methodattributes. Public | Methodattributes. Static,  Null  ,  Null  );  //  Then get the method il Generator        VaR IL = Methodbuilder. getilgenerator ();  //  Then create the method Function Il. emit (Opcodes. ldstr, "  Hello, kitty!  "  ); Il. emit (Opcodes. Call,  Typeof (Console). getmethod ( "  Writeline  " , New Type [] { Typeof ( String  )}); Il. emit (Opcodes. Call,  Typeof (Console). getmethod ("  Readline  "  ); Il. emit (Opcodes. Pop );  //  We just read something here, throw it. Il. emit (Opcodes. Ret );

Creation type,

 
//Then create the whole class typeVaRHellokittyclasstype = typebuilder. createtype ();

If the current Assembly is runnable, set a program entry,

//Set entry point for this AssemblyAssemblybuilder. setentrypoint (hellokittyclasstype. getmethod ("Sayhellomethod"));

Save the dynamically generated assembly as a disk file,

 
//Save assemblyAssemblybuilder. Save ("Kitty.exe");

Decompile kitty.exe into code through the decompilation 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 }

Running result,

Complete 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)  10   { 11         //  Specify a new Assembly name  12         VaR Assemblyname = New Assemblyname ( "  Kitty  "  );  13   14         //  Create Assembly Builder  15         VaR Assemblybuilder =Appdomain. currentdomain  16   . Definedynamicassembly (assemblyname, assemblybuilderaccess. runandsave );  17   18         //  Create module Builder  19         VaR Modulebuilder = assemblybuilder. definedynamicmodule ( "  Kittymodule  " , "  Kitty.exe "  );  20   21         //  Create type builder for a class  22         VaR Typebuilder = modulebuilder. definetype ( "  Hellokittyclass  "  , Typeattributes. Public );  23   24         //  Create method Builder 25         VaR Methodbuilder = Typebuilder. definemethod (  26           "  Sayhellomethod  "  ,  27 Methodattributes. Public | Methodattributes. Static,  28           Null  ,  29           Null  ); 30   31         //  Then get the method il Generator  32         VaR IL = Methodbuilder. getilgenerator ();  33   34         //  Then create the method Function  35 Il. emit (Opcodes. ldstr, "  Hello, kitty!  " );  36 Il. emit (Opcodes. Call, Typeof (Console). getmethod ( "  Writeline  " , New Type [] { Typeof ( String  )}));  37 Il. emit (Opcodes. Call, Typeof (Console). getmethod ( "  Readline "  ));  38 Il. emit (Opcodes. Pop ); //  We just read something here, throw it.  39   Il. emit (Opcodes. Ret );  40   41         //  Then create the whole class type  42         VaR Hellokittyclasstype = Typebuilder. createtype ();  43  44         //  Set entry point for this Assembly  45 Assemblybuilder. setentrypoint (hellokittyclasstype. getmethod ( "  Sayhellomethod  "  ));  46   47         //  Save assembly  48 Assemblybuilder. Save ( "  Kitty.exe "  );  49   50 Console. writeline ( "  Hi, Dennis, a kitty assembly has been generated for you.  "  );  51   Console. Readline ();  52   }  53   }  54 }

View code

Download complete code

Read more about using emit to generate constructors and attributes

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.