在验证用于输入数字的文本框时,有没有办法避免抛出/捕获异常?

bwe*_*rks 2 c# validation casting exception winforms

在追求优雅的编码时,我想避免必须捕获一个异常,当我尝试验证Textbox的Text字段是一个整数时,我知道可能会抛出异常.我正在寻找类似于TryGetValue for Dictionary的东西,但Convert类似乎没有提供任何东西,除了异常.

有没有可以退回布尔让我检查?

要清楚,我想避免这样做

TextEdit amountBox = sender as TextEdit;
if (amountBox == null)
    return;
try
{
    Convert.ToInt32(amountBox.Text);
}
catch (FormatException)
{
    e.Cancel = true;
}
Run Code Online (Sandbox Code Playgroud)

支持这样的事情:

TextEdit amountBox = sender as TextEdit;
if (amountBox == null)
    return;
e.Cancel = !SafeConvert.TryConvertToInt32(amountBox.Text);
Run Code Online (Sandbox Code Playgroud)

谢谢!

Mat*_*ted 13

int.TryParse 是你的朋友...

TextEdit amountBox = sender as TextEdit; 
if (amountBox == null) 
    return; 
int value;
if (int.TryParse(amountBox.Text, out value))
{
    // do something with value
    e.Cancel = false;
}
else 
{
    // do something if it failed
    e.Cancel = true;
}
Run Code Online (Sandbox Code Playgroud)

...顺便说一句,大多数私有值类型都有一个静态.TryParse(...)方法,它与上面的示例非常相似.