【发布时间】:2017-09-20 11:49:21
【问题描述】:
我正在尝试计算字符串的内容。
我有 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);
我试过this answer:
double result = (double) new DataTable().Compute("1+1*4/2-5", null);
int i = (int) result; // -2
然后我得到一个System.InvalidCastException:
指定的转换无效。
【问题讨论】:
-
在这里看看我的回答:stackoverflow.com/questions/355062/…
-
“但是我得到一个 System.InvalidCastException:” 你从哪里得到这个异常?问题结尾处代码中的 Bost 强制转换是有效的,所以我想知道你在哪里得到了异常。或者您实际传递给
Compute的字符串是什么?您可以在调试器中评估Compute调用,然后您可以检查 rtesult 和它在调试器窗口中的类型,并且您知道应该将其转换为什么(在这一行确实引发了异常)。
标签: c# arrays string datatable int