我正在处理此代码段
private void calculateButton_Click(object sender, EventArgs e)
{
int amount;
if (int.TryParse(amountTextBox.Text, out amount))
{
wantedTextBox.Text = Currency_Exchange.exchangeCurrency((Currencies)currencyComboBox.SelectedIndex, (Currencies)wantedCurrencyComboBox.SelectedIndex, amount).ToString("0.00");
wantedCurrencyLable.Text = ((Currencies)wantedCurrencyComboBox.SelectedIndex).ToString();
}
else {
MessageBox.Show("Invalid amount");
}
}
并且意识到太迟了,我应该对负数进行验证。但是我设置代码的方式使得这有点困难。我怎么能这样做?
答案 0 :(得分:2)
存储TryParse
结果的值,然后检查同一amount
语句中的if
,如下所示:
boolean parseResult = int.TryParse(amountTextBox.Text, out amount)
if (parseResult && amount >= 0)
{
//....
}
else
{
MessageBox.Show("Invalid amount");
}