首页 > 编程语言 >C# 根据用户输入的字符串 表达式进行动态计算

C# 根据用户输入的字符串 表达式进行动态计算

时间:2022-12-18 14:22:57浏览次数:40  
标签:string C# paramstr object classSource Append 字符串 expression 表达式

动态函数生成 :

/// <summary>
/// 计算公式,参数名字符,传入的参数
/// </summary>
/// <param name="expression"></param>
/// <param name="paramsNames"></param>
/// <return

   
private object CalCulate(string expression, string[] paramsNames, object[] parameters) { string className = "Calc"; string methodName = "Run"; expression = expression.Replace("/", "*1.0/"); CompilerParameters paras = new CompilerParameters(); paras.GenerateInMemory = true; StringBuilder classSource = new StringBuilder(); string paramstr= ""; if (paramsNames.Length>0) { foreach (var item in paramsNames) { paramstr += $"double {item} ,"; } } if (paramstr.Length>0) { paramstr = paramstr.Substring(0, paramstr.Length - 1); } classSource.Append("public class " + className + "\n"); classSource.Append("{\n"); classSource.Append(" public object " + methodName + $"({paramstr})\n"); classSource.Append(" {\n"); classSource.Append(" return " + expression + ";\n"); classSource.Append(" }\n"); classSource.Append("}"); //编译代码 CompilerResults result = new CSharpCodeProvider().CompileAssemblyFromSource(paras, classSource.ToString()); if (result.Errors.Count > 0) { string msg = $"Formula({className})\n"; foreach (CompilerError item in result.Errors) { msg += item.ToString() + "\r\n"; } throw new Exception(msg); } object reobj = 0 ; try { //获取编译后的程序集。 Assembly assembly = result.CompiledAssembly; //动态调用方法。 object eval = assembly.CreateInstance(className); MethodInfo method = eval.GetType().GetMethod(methodName); reobj = method.Invoke(eval, parameters); } catch (Exception ex) { throw ex; } return reobj; }

 

进行计算测试

 try
            {
                string expression = this.textBox1.Text;
                  expression ="1*2+3*4";
                  expression ="1*2+3*4+k*10+j*5";
                  expression ="1*2+3*4+k*10";
                  expression ="1*2+3*4+j*10";
                object res = CalCulate(expression, new string[] { "j", "k" }, new object[] { 10, 20 });
                  double.TryParse(res,out double resValue)
                this.textBox2.Text = resValue.ToString();
            }
            catch (Exception ex)
            {

               
            }

 

标签:string,C#,paramstr,object,classSource,Append,字符串,expression,表达式
From: https://www.cnblogs.com/JohnnyLei/p/16990339.html

相关文章