我正在尝试计算字符串的内容.
我有1个字符串,其中包含例如:MyString ="1 + 5/2*4-2"现在我想计算该字符串的结果
我是c#的新手
我的代码:
string som = "";
int myInt;
private void getText_Click(object sender, EventArgs e)
{
string s = (sender as Button).Text;
som = som + s;
Console.WriteLine(som);
string[] words = som.Split(' ');
foreach (string word in words)
{
Console.WriteLine(word);
myInt += Convert.ToInt32(word);
}
Console.WriteLine(myInt);
Run Code Online (Sandbox Code Playgroud)
我试过这个答案:
double result = (double) new DataTable().Compute("1+1*4/2-5", null);
int i = (int) result; // -2
Run Code Online (Sandbox Code Playgroud)
但后来我得到了System.InvalidCastException:
指定演员表无效.