Dynamic generation and compiling source code

zhaozj2021-02-16  55

/ Enter your code you want to test, then display it, it feels more convenient.

// dynamically generate and compile the source code using Microsoft.CSharp; using System; using System.CodeDom; using System.CodeDom.Compiler; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; Using system.data; using system.io;

namespace cjl {public delegate string Run (); public class Form1: System.Windows.Forms.Form {Run run; private System.Windows.Forms.Label label2; private System.Windows.Forms.Button RunCode; private System.Windows. Forms.TextBox Code; private system.windows.forms.label result; private system.windows.forms.textbox codeput; private system.componentmodel.container components = null;

Public form1 () {initializationComponent ();

Protected Override Void Dispose (bool disposing) {if (disponents! = null) {components.dispose ();}} Base.Dispose (Disposing);

#Region Windows Form Designer Generated Code

private void InitializeComponent () {this.RunCode = new System.Windows.Forms.Button (); this.Code = new System.Windows.Forms.TextBox (); this.Result = new System.Windows.Forms.Label () This.label2 = new system.windows.forms.label (); this.codeoutput = new system.windows.forms.textbox (); this.suspendlayout (); // // runcode // this.Runcode.location = New system.drawing.point (40, 104); this.Runcode.name = "runcode"; this.Runcode.size = new system.drawing.size (336, 23); this.Runcode.tabindex = 1; this. Runcode.text = "Run Code"; this.Runcode.Click = new system.eventhandler (this.button1_click); //// code // this.code.location = new system.drawing.point (40, 16) This.code.multiline = true; this.code.name = "code"; this.code.size = new system.drawing.size (336, 80); this.code.tabindex = 2; this.code.text = "// The last sentence must be return string type / r / nint i = 2; / r / nstring s = /" ssss / "; / r / nreturn string.concat (i, s);"; // // Result // this.Result.location = New system.drawing.point (40, 136); this.Result.name = "result"; this.Result.size = new system.drawing.size (336, 160); this.Result.tabindex = 3; this. Result.text = "Display Results"; // // Label2 // this.Label2.Location = New System.drawing.Point (0, 24); this.Label2.name = "label2"; this.label2.size = New system.drawing.size (32, 23); this.label2.tabindex = 4; this.label2.text = "code"; /// codeput // this.codeoutput.location = new system.drawing.point ( 384, 16); this.codeoutput.multiline = true;

this.codeOutput.name = "codeput"; this.codeoutput.size = new system.drawing.size (320, 288); this.codeoutput.tabindex = 5; this.codeoutput.text = ""; // // Form1 // this.autoscalebasesize = new system.drawing.size (6, 14); this.clientsize = new system.drawing.size (712, 317); this.Controls.addrange (new system.windows.forms.control [] {This.codeOutput, this.label2, this.result, this.code, this.runcode}; this.name = "form1"; this.text = "form1"; this.ResumeLayout (false);} #ENDREGION

[Stathread] static void main () {application.run (new form1 ());}

Private void button1_click (object sender, system.eventargs e) {if (this.code.text.lastIndexof ("Return") <0) {String Message = "must contain Reuturn, and the type returned is String type."; MessageBox .Show; result.text = message; return;

CsharpcodeProvider CodeProvider = new csharpcodeProvider (); icodegenerator codeGenerator = codeProvider.createGenerator ();

CODENAMESPACE NS = New CodenameSpace ("CJL"); ns.comments.add (New CodeCommentStatement);

// If an error occurs at runtime, it is possible that the code you entered in other namespaces, add more CODENAMESPACEIMPORT NS.IMPORTS.ADD ("system"); ns.imports.add ( New CodeNameSpaceImport ("System.IO"));

CODETYPEDECLATION TESTCLASS = New CodeTypedeclaration ("test"); testclass.typeattributes = typettributes.public; testclass.isclass = true; ns.types.add (testclass);

CodeMemberMethod function = new CodeMemberMethod (); function.Attributes = MemberAttributes.Public; function.Name = "Try"; function.ReturnType = new CodeTypeReference (typeof (string)); foreach (string s in this.Code.Text.Split ( ';')) {Function.Statements.Add (New CodesnippetStatement);}

testClass.Members.Add (function); // write the file TextWriter writer = new StreamWriter (new FileStream ( "Temp.cs", FileMode.Create)); CodeGeneratorOptions options = new CodeGeneratorOptions (); options.BracingStyle = "C" Codegenerator.GeneratecodefromNamespace (NS, Writer, Options); Writer.close ();

CodeOutput.text = New StreamReader (New FileStream ("Temp.cs", FileMode.Open). ReadToend ();

CodeCompileUnit compileUnit = new CodeCompileUnit (); compileUnit.Namespaces.Add (ns); CompilerParameters compilerParameters = new CompilerParameters (); compilerParameters.GenerateInMemory = true; ICodeCompiler csharpCompiler = codeProvider.CreateCompiler (); CompilerResults compilerResults = csharpCompiler.CompileAssemblyFromDom (compilerParameters, compileUnit ); if (compilerResults = null && compilerResults.Errors.Count> 0)! {foreach (CompilerError err in compilerResults.Errors) {Result.Text = err.ToString () "/ n";}} object o = compilerResults. Compiledassembly.createInstance ("cjl.test", true); run = (run) delegate.createdelegate (TypeOf (run), o, function.name; this.result.text = "Run the above code results as follows: / N / N " Run ();}}}

转载请注明原文地址:https://www.9cbs.com/read-19336.html

New Post(0)