Communicating with dynamically executed C # code

Source: Internet
Author: User
Tags foreach execution trim

1. Introduction

The ability to dynamically execute C # code is a cool feature, for example, we can enter a line of C # code in the console, and the program automatically compiles and executes the line of code and displays the results to us. This is almost the simplest C # code interpreter.

Dynamic execution of C # code is also a useful function, for example, we can write some code in a file, by the Assembly at the time of execution loading, change the code does not stop the program, when the program to load the code, automatically executes the new code.

Next, I'm going to write a simple C # code interpreter, and then add a dynamic interaction mechanism between the dynamic code and the interpreter environment in the C # code interpreter to demonstrate a very good and powerful application.

2. Simple C # code interpreter

The article on how to dynamically execute C # code is clearly described in the Jailu.net how to dynamically compile and execute code in C #. Write a C # code interpreter using the way described in this article:

Using System;
Using System.Collections.Generic;
Using System.Reflection;
Using System.Globalization;
Using Microsoft.csharp;
Using System.CodeDom;
Using System.CodeDom.Compiler;
Using System.Text;
Using System.IO;
Using System.Xml;
Namespace Test
{
Class Program
{
static void Main (string[] args)
{
Console.Write (">>");
String cmd;
Context CXT = new context ();
while (cmd = Console.ReadLine (). Trim ())!= "Exit")
{
if (! String.IsNullOrEmpty (CMD))
{
Console.WriteLine ();
Cxt. Invoke (CMD);
}
Console.Write ("\n>>");
}
}
}
public class context
{
Public CSharpCodeProvider Codeprovider {get; set;}
Public idictionary<string, assembly> Assemblys {get; set;}
Public context ()
{
Codeprovider = new CSharpCodeProvider (new dictionary<string, string> () {{"CompilerVersion", "v3.5"}});
Assemblys = new dictionary<string, assembly> ();
Assembly[] Al = AppDomain.CurrentDomain.GetAssemblies ();
foreach (Assembly A in AL)
{
Addassembly (a);
}
AppDomain.CurrentDomain.AssemblyLoad + = new Assemblyloadeventhandler (currentdomain_assemblyload);
}
private void addassembly (Assembly a)
{
if (a!= null)
{
Assemblys.add (A.fullname, a);
}
}
void Currentdomain_assemblyload (object sender, Assemblyloadeventargs args)
{
Assembly a = args. loadedassembly;
if (! Assemblys.containskey (A.fullname))
{
Addassembly (a);
}
}
Public CompilerParameters createcompilerparameters ()
{
CompilerParameters cp = new CompilerParameters ();
Cp. GenerateExecutable = false;
Cp. GenerateInMemory = true;
if (Assemblys!= null)
{
foreach (Assembly A in assemblys.values)
{
Cp. Referencedassemblies.add (a.location);
}
}
return CP;
}
public void Invoke (String cmd)
{
String inputcmdstring = cmd. Trim ();
if (String.IsNullOrEmpty (inputcmdstring)) return;
String fullcmd = Buildfullcmd (inputcmdstring);
CompilerResults cr = Codeprovider.compileassemblyfromsource (Createcompilerparameters (), FULLCMD);
if (CR. Errors.haserrors)
{
Boolean Recompileswitch = true;
foreach (CompilerError err in CR. Errors)
{
Cs0201:only assignment, call, increment, decrement, and new object expressions can
Used as a statement
if (!err. Errornumber.equals ("CS0201"))
{
Recompileswitch = false;
Break
}
}
Re-compiling
if (Recompileswitch)
{
String dynaname = "Temparg_dynamic_" + DateTime.Now.Ticks.ToString ();
inputcmdstring = String.Format ("var {0} =", dynaname) + inputcmdstring;
Inputcmdstring + = "; \ n System.Console.WriteLine (" + Dynaname + ");";
Fullcmd = Buildfullcmd (inputcmdstring);
CR = Codeprovider.compileassemblyfromsource (Createcompilerparameters (), fullcmd);
}
if (CR. Errors.haserrors)
{
Console.WriteLine ("Compile Error:");
foreach (CompilerError err in CR. Errors)
{
Console.WriteLine (Err. ErrorNumber);
Console.WriteLine (Err. ErrorText);
}
Return
}
}
Assembly Assem = cr.compiledassembly;
Object dynamicobject = Assem. CreateInstance ("Test.dynamicclass");
Type t = Assem. GetType ("Test.dynamicclass");
MethodInfo minfo = T.getmethod ("MethodInstance");
Minfo. Invoke (dynamicobject, NULL);
}
private string Buildfullcmd (String inputcmdstring)
{
String fullcmd = String.Empty;
Fullcmd = @ "
Namespace Test
{
public class DynamicClass
{
public void MethodInstance ()
{
"+ inputcmdstring + @";
}
}
}";
return fullcmd;
}
}
}

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.