//首先要包含必要的命名空间
using Microsoft.CSharp;
public double Calculate(string formula)
{
CSharpCodeProvider provider = new CSharpCodeProvider();
CompilerParameters parameter = new CompilerParameters();
parameter.ReferencedAssemblies.Add("System.dll");
parameter.GenerateExecutable = false; //<--不生成exe
parameter.GenerateInMemory = true; //<--直接在内存运行
CompilerResults result = provider.CompileAssemblyFromSource(
parameter, GenerateCodeBlocks(formula));
//动态编译(VisualStudio)
if (result.Errors.Count > 0)
return 0;
//编译成功-调用编译后的代码
double calculated = Convert.ToDouble(result.CompiledAssembly.
GetType("demo.calculation").GetMethod("dowork").Invoke(null, null));
//这里通过反射调
return calculated;
}
//得到要编译的C#代码
string GenerateCodeBlocks(string formula)
{
string code =
"using System;" +
"namespace demo" +
"{" +
"public static class calculation" +
"{ " +
"public static double dowork()" +
"{ " +
" return " + formula + ";" +
"} " +
"} " +
"} ";
return code;
}
/*
* //该函数会得到这样的一段C#代码
* using System;
* namespace demo
* {
* public static class calculation
* {
* public static double dowork()
* {
* // 如果formula是 1+2/3*4
* // 那么,下面这句就是 return 1+2/3*4;
* return ...
* }
* }
* }
*
* //然后在Calculate()函数中调用这段代码就会得到四则运算表达式的结果
* //result.CompiledAssembly.GetType("demo.calculation").
* // GetMethod("dowork").Invoke(null,null)
*/