/// <summary>
/// 将字符串中的运算符按正常计算 例如按四则运算
/// </summary>
/// <param name="expression">标准表达式如 1+15*0.5-200</param>
/// <returns>返回计算的值,可以为任意合法的数据类型</returns>
protected static object MathCalculate(string expression)
{
object retvar = null;
Microsoft.CSharp.CSharpCodeProvider provider = new Microsoft.CSharp.CSharpCodeProvider();
System.CodeDom.Compiler.CompilerParameters cp = new System.CodeDom.Compiler.CompilerParameters(
new string[] { @"System.dll" });
StringBuilder builder = new StringBuilder("using System;class CalcExp{public static object Calc(){ return \"expression\";}}");
builder.Replace("\"expression\"", expression);
string code = builder.ToString();
System.CodeDom.Compiler.CompilerResults results;
results = provider.CompileAssemblyFromSource(cp, new string[] { code });
if (results.Errors.HasErrors)
{
retvar = null;
}
else
{
System.Reflection.Assembly a = results.CompiledAssembly;
Type t = a.GetType("CalcExp");
retvar = t.InvokeMember("Calc", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.InvokeMethod
, System.Type.DefaultBinder, null, null);
}
return retvar;
}
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步