Example of a dynamic compilation

Source: Internet
Author: User
Tags eval expression string tostring
compiling | dynamic | compiling using System;
Using System.CodeDom.Compiler;
Using Microsoft.csharp;
Using System.Reflection;
Using System.Text;

Namespace ConsoleApplication22
{
<summary>
Summary description of the CLASS1.
</summary>
Class Class1
{
<summary>
The main entry point for the application.
</summary>
[STAThread]
static void Main (string[] args)
{
//
TODO: Add code here to start the application
//
int i = (int) Calc ("1+2*3");
Console.WriteLine (i.ToString ());
Console.ReadLine ();

}

public static object Calc (string expression)
{
String className = "Calc";
String methodname = "Run";
Expression=expression. Replace ("/", "*1.0/");

Creates a compiler instance.
ICodeCompiler complier = (new CSharpCodeProvider (). CreateCompiler ());
Sets compilation parameters.
CompilerParameters paras = new CompilerParameters ();
paras. GenerateExecutable = false;
paras. GenerateInMemory = true;

Create dynamic code.
StringBuilder Classsource = new StringBuilder ();
Classsource.append ("public class" + ClassName + "\ n");
Classsource.append ("{\ n");
Classsource.append ("public object" + methodname + "() \ n");
Classsource.append ("{\ n");
Classsource.append ("return" + expression + "; \ n");
Classsource.append ("}\n");
Classsource.append ("}");

System.Diagnostics.Debug.WriteLine (Classsource.tostring ());

Compile the code.
CompilerResults result = Complier.compileassemblyfromsource (paras, classsource.tostring ());

Gets the compiled assembly.
Assembly Assembly = result.compiledassembly;

Dynamic invocation method.
Object eval = assembly. CreateInstance (ClassName);
MethodInfo method = eval. GetType (). GetMethod (methodname);
Object Reobj = method. Invoke (eval, null);
Gc. Collect ();
return reobj;

}

}
}





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.