c# - 如何实现调用自身的方法?

标签 c# recursion loops

我的手腕被打了一巴掌,因为在一次作业中,当出现输入错误时,我有一个方法会自行调用。我不知道如何使用或使用什么来代替我编写的代码。我需要帮助才能找到正确的方法。

我喜欢编码,所以我只需要以正确的方式插入它! :)

我写的代码是这样的。

 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/

相关文章:

c# - 如何将对象时间戳与对象 ID 连接起来并将它们传递给操作方法

c# - 如何使用 C# 将颜色(在 RGB 模式下)转换为 PNG 的透明色?

mysql - 如何递归地从表中删除项目?

recursion - 初学者方案 : Procedures that return themselves

C++ 拉取信息并循环显示

c# - 循环 2 个数组 (Unity3d)

c# - ElasticSearch (Nest) 中的聚合

javascript - 递归查找数组中的项目并从引用数组中拼接出找到的项目

Java:方法总是返回相同的结果

循环访问 AWS 命令​​行客户端输出的 Bash 脚本