第一種解決方案
第一種也是功能最強大的一種,能夠使用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接口