2011-08-10 183 views
1

使用VS2010 Express,C#及其WinForms应用程序。解析陷阱

这里我有三个文本框(aTextBox,bTextBox,cTextBox),其中Inputs是字符串,然后使用int.Parse(aTextBox.Text)转换为整数。

那么问题是通过使按钮(calcBtn)方法,该方法是要计算费用,然后显示一些数学上这又包含了结果的文本框结果GROUPBOX特定文本框后的结果...

我解析的方式或它执行的顺序。如果任何文本框被填充,则结果应该显示,而不是格式异常。在这里,我陷入了困境,因为在calcBtn里我解析了所有的文本框,如果其中一个是空的,那么会发生异常。编译器是我想要解析空文本框中的空字符串,我不希望它是。

任何建议,如果你明白我的意思? :)

这里的GUI是什么样子 enter image description here

回答

2

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; 
} 

您采取的方法取决于您的应用程序的具体需求。

+0

没有决策声明的任何可能性? –

+0

@Jasmine Appelblad为什么你不想使用if语句? – Odnxe

+0

@Odnxe这是来自讲义的练习,它不包含决定主题,也是我讲师的要求。 –

3

您可以使用扩展方法...

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(); 
0

你可以简单地做:

private static int ParseInteger(string str) 
{ 
    int value; 
    Int32.TryParse(str, out value); 
    return value; 
} 

无任何如果自TryParse设置值t如果它失败,则为0