有一种更好的方法可以避免在 Console.ReadLine 中输入空值而不是 if 语句

There is a better way of avoiding null inputs in Console.ReadLine instead of if statements

现在代码一切正常,但有更好的方法来避免 Console.ReadLine 中的空输入,我已经尝试过 if 语句,但代码最终看起来一团糟。

class ColocarMoedas
{
    public static void Colocar(MaquinaUsuario user)
    {
        int m1, m5, m10, m25, m50;

        Console.Clear();
        Console.WriteLine("/////////////////////////MOEDAS////////////////////////////");
        Console.Write("1 Centavo: ");
        m1 = int.Parse(Console.ReadLine());

        Console.Write("5 Centavo: ");
        m5 = int.Parse(Console.ReadLine());

        Console.Write("10 Centavo: ");
        m10 = int.Parse(Console.ReadLine());

        Console.Write("25 Centavo: ");
        m25 = int.Parse(Console.ReadLine());

        Console.Write("50 Centavo: ");
        m50 = int.Parse(Console.ReadLine());

        user.Adicionar(m1, m5, m10, m25, m50);

        Console.Clear();
    }
}

There is a better way of avoiding null inputs in Console.ReadLine instead of if statements

答案是肯定的。

虽然值得注意,但 用户输入 可能出错的地方不仅仅是 null。事实上 null 非常罕见,这是您需要担心的其他一切。

验证用户数字输入的最惯用方法是使用TryParse样式方法,return a bool 当值不能被 parsed 和 returns a value through an out参数当true.

Int32.TryParse Method

Converts the string representation of a number to its 32-bit signed integer equivalent. A return value indicates whether the operation succeeded.

您可以使用验证循环更进一步

int m1 = 0;
while (!int.TryParse(Console.ReadLine(), out m1))
   Console.WriteLine("You hard one job! Now try again");

基本上上面说了,虽然数字无法转换为整数,其中包括错别字,空输入和Ctrl+c(null),请留言。