第一种解决方案
第一种也是功能最强大的一种,能够使用Eval函数,像在Java中同样强大,几乎全部的运算符均可以实现,包括四则运算,与或非等。html
添加COM引用:函数
private void button2_Click(object sender, EventArgs e) { MSScriptControl.ScriptControl sc = new MSScriptControl.ScriptControlClass(); sc.Language = "JavaScript"; MessageBox.Show(sc.Eval("((2*3)-5+(3*4))+6/2").ToString());//1+12+3 }
在引用COM组件的时候,出现了没法嵌入互操做类型“……”,请改用适用的接口的错误提示。查阅资料,找到解决方案,记录以下:性能
选中项目中引入的dll,鼠标右键,选择属性,把“嵌入互操做类型”设置为False。spa
第贰种解决方案
简单的四则运算或判断能够使用DataTable.Compute来实现。code
DataTable dt = new DataTable(); MessageBox.Show(dt.Compute("1*2+3", "false").ToString());
//替换公式 string formula = "K*(F0+Fi)"; double K = 0.0D, F0 = 3.0F, Fi = 10.0F; formula = formula.Replace("K", "{0}"); formula = formula.Replace("F0", "{1}"); formula = formula.Replace("Fi", "{2}"); formula = string.Format(formula, K, F0, Fi); DataTable dt = new DataTable(); string really_data = dt.Compute(formula, "false").ToString();
第叁种解决方案
第三种比较耗费性能,局限性较大,就是在用SQL语句来实现。SQL中的select语句也能够实现计算。orm
string strConn = "Data Source=127.0.0.1;Initial Catalog=CementCartDB;Persist Security Info=True;User ID=sa;Password=123456" conn = new SqlConnection(strConn); conn.Open(); cmd = conn.CreateCommand(); string biaodashi = "1&1"; cmd.CommandText = "select "+biaodashi; string o = cmd.ExecuteScalar().ToString(); MessageBox.Show(o);
以上是我总结的字符串转换为运算符的几种方式。本身备份的同时但愿对你们也有所帮助。htm
转载地址blog
评论给出的其余办法:文中的三种方法均不太好,还有一种更好的方法,可参考: https://pzy.io/archives/2019/10/calculating-string-formula.html接口