小编EG4*_*G47的帖子

计算字符串的内容为int

我正在尝试计算字符串的内容.

我有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:

指定演员表无效.

c# arrays string int datatable

0
推荐指数
1
解决办法
81
查看次数

标签 统计

arrays ×1

c# ×1

datatable ×1

int ×1

string ×1