In-depth introduction to. Net code generation series (7): A comprehensive example of dynamic generation of code and compilation

Source: Internet
Author: User

As we have mentioned above, you may feel that you haven't made any things.

This is a comprehensive example. It consists of two parts: the first part, generating code and outputting it to the console window. The second part, dynamically compiling the code, A winform application is generated. You can double-click the dynamically compiled program to run it. click the button in the window to bring up a dialog box.

Well, I will paste the code of the entire example below. It's very easy. You just need to create a new console application.

Using system; using system. collections. generic; using system. LINQ; using system. text; using system. codedom; using system. codedom. compiler; namespace example {class program {static void main (string [] ARGs) {codecompileunit myunit = new codecompileunit (); // a namespace codenamespace mynamespace = new codenamespace ("MyApp"); mynamespace. imports. add (New codenamespaceimport ("system"); mynamespace. imports. add (n EW codenamespaceimport ("system. windows. forms "); mynamespace. imports. add (New codenamespaceimport ("system. drawing "); mynamespace. imports. add (New codenamespaceimport ("system. text "); // defines a class codetypedeclaration myclass = new codetypedeclaration (" mainform "); myclass. attributes = memberattributes. public; myclass. basetypes. add (New codetypereference ("form"); codememberfield buttonfield = new codememb Erfield ("button", "button1"); buttonfield. initexpression = new codeprimitiveexpression (null); myclass. members. add (buttonfield); // constructor myconstr = new codeconstructor (); // instantiate the button class myconstr. statements. add (New codeassignstatement (New codefieldreferenceexpression (New codethisreferenceexpression (), "button1"), new codeobjectcreateexpression ("button", new codeexpression [] {});/ /Assign myconstr to the related properties of the button instance. statements. add (New codeassignstatement (New codepropertyreferenceexpression (New codefieldreferenceexpression (New evaluate (), "button1"), "text"), new codeprimitiveexpression ("Click here"); myconstr. statements. add (New codeassignstatement (New codepropertyreferenceexpression (New codefieldreferenceexpression (New codethisreferenceexpression (), "button1 ")," Width "), new codeprimitiveexpression (INT) 285); myconstr. statements. add (New codeassignstatement (New codepropertyreferenceexpression (New codefieldreferenceexpression (New evaluate (), "button1"), "height"), new codeprimitiveexpression (INT) 65); myconstr. statements. add (New codeassignstatement (New codepropertyreferenceexpression (New codefieldreferenceexpression (New codethisre Ferenceexpression (), "button1"), "location"), new codeobjectcreateexpression ("point", new codeprimitiveexpression (INT) 60), new codeprimitiveexpression (INT) 80); // bind the button's Click Event myconstr. statements. add (New codeattacheventstatement (New codefieldreferenceexpression (New codethisreferenceexpression (), "button1"), "click", new codemethodreferenceexpression (New codethisreferenceexpression (), "B Utton1_click "); // you can specify the width and height of the window. statements. add (New codeassignstatement (New codepropertyreferenceexpression (New codethisreferenceexpression (), "width"), new codeprimitiveexpression (INT) 450); myconstr. statements. add (New codeassignstatement (New codepropertyreferenceexpression (New codethisreferenceexpression (), "height"), new codeprimitiveexpression (INT) 300); // set the window title myconstr. stat Ements. add (New codeassignstatement (New codepropertyreferenceexpression (New codethisreferenceexpression (), "text"), new codeprimitiveexpression ("My applications "))); // Add the button variable to myconstr in the form control set. statements. add (New codeexpressionstatement (New codemethodinvokeexpression (New codepropertyreferenceexpression (New codethisreferenceexpression (), "controls"), "add", new codefieldreferenceexpression (New codet Hisreferenceexpression (), "button1"); myclass. members. add (myconstr); // click the handler codemembermethod myhandlermethod = new codemembermethod (); myhandlermethod. attributes = memberattributes. private; myhandlermethod. name = "button#click"; myhandlermethod. parameters. add (New codeparameterdeclarationexpression ("object", "sender"); myhandlermethod. parameters. add (New codeparameterdeclarationexpression ("Eventargs", "E"); // description of myhandlermethod in the method. statements. add (New codeexpressionstatement (New codemethodinvokeexpression (New codetypereferenceexpression ("MessageBox"), "show", new codeprimitiveexpression ("Hello, click here. "); // Add the method to the class member myclass. members. add (myhandlermethod); // Add the class to the namespace mynamespace. types. add (myclass); // Add the namespace to the compilation unit myunit. namespaces. add (mynamespace); // The entry point function codeentrypointmethod main = new codeentrypointmethod (); main. statements. add (New codeexpressionstatement (New codemethodinvokeexpression (New codetypereferenceexpression ("application"), "run", new codeobjectcreateexpression ("mainform ", New codeexpression [] {}); myclass. members. add (main); // output the generated code codedomprovider provider = codedomprovider. createprovider ("CS"); provider. generatecodefromcompileunit (myunit, console. out, new codegeneratoroptions {bracingstyle = "C"}); // compile the Assembly compilerparameters Param = new compilerparameters (); Param. compileroptions = @ "/T: winexe/out: myapp.exe"; Param. includedebuginformation = false; PA Ram. referencedassemblies. add ("mscorlib. DLL "); Param. referencedassemblies. add ("system. drawing. DLL "); Param. referencedassemblies. add ("system. windows. forms. DLL "); Param. referencedassemblies. add ("system. DLL "); compilerresults result = provider. compileassemblyfromdom (Param, myunit); If (result. errors. count! = 0) {console. writeline ("\ n --------------------- compilation error ------------------------"); foreach (compilererror err in result. errors) {console. writeline ("information: {0}", err. errortext) ;}} else {console. writeline ("compiled successfully. ") ;}Console. readkey ();}}}

Run the program. The code is generated and compiled, as shown in.

 

So where is the generated winform program? The/out: myapp.exe parameter is used in the above Code. Where is this EXE, and the relative path is in the same directory as the current application, open the location of your project and find \ bin \ Debug. Do you see the myapp.exe? Double-click to run the task. Okay. A miracle happened.

 

How is it? This is a bit of a thing, right?

To sum up, this dynamic generation of code, to tell the truth, usually does not have a lot of opportunities to use it, so I did not elaborate on it. Furthermore, it is not complicated to use, but it is painful to think about it. So someone asked, What is the use of dynamic generation or dynamic compilation in actual applications? Haha, I am joking to answer you: be a Trojan! Haha.

 

 

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.