C# 公式計算(字符串)


 

1)調用JS計算方法(不推薦,效率低)

MSScriptControl.ScriptControl scriptControl = new MSScriptControl.ScriptControl();
scriptControl.Language = "JScript";
string value = scriptControl.Eval("1+2*(4-3)").ToString();
Console.WriteLine(value);

 

2)使用DataTable的Compute()方法

DataTable table = new DataTable();
string value = table.Compute("1+2*(4-3)", "").ToString();
Console.WriteLine(value);

 

3)構建DataTable,給列名添加公式

//計算公式
string expression1 = "a+b*(c-d)";
string expression2 = "a+b-c-d";

//構建table
DataTable table = new DataTable();
table.Columns.Add("a", typeof(int));
table.Columns.Add("b", typeof(int));
table.Columns.Add("c", typeof(int));
table.Columns.Add("d", typeof(int));
table.Columns.Add("e1", typeof(int));//公式列
table.Columns.Add("e2", typeof(int));//公式列

//添加公式
table.Columns["e1"].Expression = expression1;
table.Columns["e2"].Expression = expression2;

//添加一行並賦值
DataRow row = table.Rows.Add();
row["a"] = 1;
row["b"] = 2;
row["c"] = 4;
row["d"] = 3;

table.BeginLoadData();
table.EndLoadData();

for (int i = 0; i < table.Columns.Count; i++)
{
Console.Write(table.Columns[i].ColumnName + "\t");
}

Console.WriteLine();

for (int i = 0; i < table.Columns.Count; i++)
{
Console.Write(row[i].ToString() + "\t");
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM