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;
}
}
}