C#动态编译表达式

下面是原始方案
public object ComplierCode(string expression, ILogService logService, out string errorString)
{
string code = WrapExpression(expression);
object retvalue = null;
errorString = “”;
CSharpCodeProvider csharpCodeProvider = new CSharpCodeProvider();
try
{
//编译的参数
CompilerParameters compilerParameters = new CompilerParameters
{
CompilerOptions = “/t:library”,
GenerateInMemory = true
};
//开始编译
CompilerResults compilerResults = csharpCodeProvider.CompileAssemblyFromSource(compilerParameters, code);
if (compilerResults.Errors.Count > 0)
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < compilerResults.Errors.Count; i++) { sb.Append(sb.Length > 0 ? “;” : “”);
sb.Append(compilerResults.Errors[i].ErrorText);
}
errorString = sb.ToString();
throw new Exception(“编译出错!” + sb.ToString());
}

Assembly assembly = compilerResults.CompiledAssembly;
Type type = assembly.GetType(“ExpressionCalculate”);
MethodInfo method = type.GetMethod(“Calculate”);
retvalue = method.Invoke(null, null);
}
catch (Exception ex)
{
logService.WriteLog(“编译出错,code=” + code, ex);
}
finally
{
csharpCodeProvider.Dispose();
}
return retvalue;
}

private string WrapExpression(string expression)
{
string code = @”
using System;

class ExpressionCalculate
{
public static object Calculate()
{
return {0};
}
}
“;
return code.Replace(“{0}”, expression);
}
其他方案:https://github.com/davideicardi/DynamicExpresso