我的手腕被打了一巴掌,因为在一次作业中,当出现输入错误时,我有一个方法会自行调用。我不知道如何使用或使用什么来代替我编写的代码。我需要帮助才能找到正确的方法。
我喜欢编码,所以我只需要以正确的方式插入它! :)
我写的代码是这样的。
private void SumTheNumbers()
{
Console.Write("Please give the value no "+ index + " :");
if (false == int.TryParse(Console.ReadLine(), out num))
{
//Errormessage if the user did not input an integer.
Console.WriteLine("Your input is not valid, please try again.");
Console.WriteLine();
sum = 0;
SumTheNumbers();
}
else
{
//Calculate the numbers given by user
sum += num;
}
}
最佳答案
我个人有点喜欢这种风格,但它效率低下(如果用户多次输入无效输入,可能会导致堆栈溢出)。您的讲师可能希望您使用 while
循环:
Console.Write("Please give the value no "+ index + " :");
while (false == int.TryParse(Console.ReadLine(), out num))
{
//Errormessage if the user did not input an integer.
Console.WriteLine("Your input is not valid, please try again.");
Console.WriteLine();
sum = 0;
}
//Calculate the numbers given by user
sum += num;
顺便说一句,false ==
位非常不合惯用语,并且会引起大多数团队的注意(旁注:如果您的导师建议您这样写,他/她可能来自不同的语言背景,它可以防止意外赋值;相信我,在 C# 领域这不是必需的或正常的)。这看起来更典型:
while (!int.TryParse(Console.ReadLine(), out num))
{
// etc.
}
关于c# - 如何实现调用自身的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11418750/