【发布时间】:2016-07-27 09:14:22
【问题描述】:
我正在尝试将用户在文本框中输入的数字添加到数字中。操作相当简单,但我被要求尽可能优化代码。到目前为止,我已经创建了一个方法来验证 textBox 是否为空。然后我有一种将文本框中的字符串转换为“int”的方法。但是,现在我不知道如何获得这些数字并在我的“求和”方法中使用它们。也许我忘记了一些基本的东西。
这是我的代码:
private void btnSum_Click(object sender, RoutedEventArgs e)
{
String num1 = txtNum1.Text;
String num2 = txtNum2.Text;
if(validate(num1,num2) == false)
{
MessageBox.Show("Empty fields");
}
else
{
convertNum(num1, num2);
MessageBox.Show("The sum is: ");
}
}
public static Boolean validate(String n1, String n2)
{
if (n1 == null || n1.Equals("") || n2 == null || n2.Equals(""))
{
return false;
}
else
{
return true;
}
}
public static void convertNum(String n1,String n2)
{
int num1 = 0;
int num2 = 0;
try
{
num1 = Int32.Parse(n1);
num2 = Int32.Parse(n2);
}catch(FormatException)
{
MessageBox.Show("Input only numbers.");
}
}
public static int sum(int n1, int n2)
{
int sum = n1 + n2;
return sum;
}
【问题讨论】:
-
“优化”是什么意思?您的意思是“更快”还是“减少代码”?
-
最好使用
int.TryParse而不是int.Parse并捕获异常。 -
将大部分操作转化为方法。