使用VS2010 Express、C#及其WinForms应用程序。
这里我有三个文本框(aTextBox、bTextBox、cTextBox),它们的输入是字符串,然后使用int.Parse(aTextBox.Text)转换为整数。
然后是一个按钮(calcBtn)方法,它将计算费用,然后将一些数学运算后的结果显示给Result groupBox上的特定TextBoxes,它同样包含结果的文本框……
这个问题是由我解析的方式或它执行的顺序引起的。如果填充了任何文本框,则应显示结果,而不是get格式异常。在这里,我被卡住了,因为在calcBtn中,我正在解析所有的文本框,如果其中一个是空的,那么就会发生异常。编译器我猜是试图从空文本框中解析空字符串,但我不希望这样。
如果你明白我的意思,有什么建议吗?:)
下面是GUI的外观

发布于 2011-08-10 10:24:48
Int32.Parse方法不接受格式错误的字符串,这包括空字符串。我有两个建议。
您可以先检查字符串是否为空/空格,然后返回0或其他一些默认值:
private static int ParseInteger(string str)
{
if (str == null || str.Trim() == "")
return 0;
// On .NET 4 you could use this instead. Prior .NET versions do not
// have the IsNullOrWhiteSpace method.
//
// if (String.IsNullOrWhiteSpace(str))
// return 0;
return Int32.Parse(str);
}或者,您可以简单地忽略所有解析错误,将它们视为0。这会将""、"123abc"和"foobar"等内容视为零。
private static int ParseInteger(string str)
{
int value;
if (Int32.TryParse(str, out value))
return value;
return 0;
}采用哪种方法取决于您的应用程序的特定需求。
发布于 2011-08-10 10:31:25
您可以使用扩展方法...
1)方法
public static class TE
{
public static int StringToInt(this string x)
{
int result;
return int.TryParse(x, out result) ? result : 0;
}
}2)使用
System.Windows.Forms.TextBox t = new System.Windows.Forms.TextBox();
int x = t.Text.StringToInt();发布于 2011-08-10 12:56:45
您可以简单地这样做:
private static int ParseInteger(string str)
{
int value;
Int32.TryParse(str, out value);
return value;
}不带任何if,因为TryParse会在失败时将值设置为0
https://stackoverflow.com/questions/7005191
复制相似问题