代码之家  ›  专栏  ›  技术社区  ›  Suraj

在C#中,如何将键盘上的空输入转换为可空类型的布尔变量?

  •  -5
  • Suraj  · 技术社区  · 8 年前

    我想做这样的事-

    using System;
    
    class MainClass
    {
        public static void Main ()
        {
            bool? input;
            Console.WriteLine ("Are you Major?");
            input = bool.Parse (Console.ReadLine ());
            IsMajor (input); 
    
        }
    
    
        public static void IsMajor (bool? Answer)
        {
            if (Answer == true) {
                Console.WriteLine ("You are a major");
            } else if (Answer == false) {
                Console.WriteLine ("You are not a major");
            } else {
                Console.WriteLine ("No answer given");
            }
        }
    
    }
    

    这里,如果用户没有给出答案,只需按enter键,则变量输入必须存储该值 null 和输出必须为 No answer given .

    在我的代码中,输入 true false 工作正常。

    但是如果没有输入,并且按下enter键,编译器将抛出异常

    System.FormatExeption has been thrown
    String was not recognized as a valid Boolean
    

    那么如何获得 无效的 存储在变量中的值 input 所以输出是 未给出答案

    在这里

    问题是 String was not recognized as a valid boolean C#

    显然不是重复的,因为它不想直接从键盘获取空输入。如果不能接受这样的输入,那么nullable类型的实用程序是什么,因为也会有解决方法?

    3 回复  |  直到 8 年前
        1
  •  4
  •   JohnyL    8 年前
    bool input;
    Console.WriteLine("Are you Major?");
    if (!bool.TryParse(Console.ReadLine(), out input))
    {
        Console.WriteLine("No answer given");
    }
    else
    {
        //....
    }
    

    或使用 C#7 :

    if (!bool.TryParse(Console.ReadLine(), out bool input))
    {
        Console.WriteLine("No answer given");
    }
    else
    {
        // Use "input" variable
    }
    // You can use "input" variable here too
    
        2
  •  2
  •   mjwills Myles McDonnell    8 年前
    bool? finalResult = null;
    bool input = false;
    
    Console.WriteLine("Are you Major?");
    
    if (bool.TryParse(Console.ReadLine(), out input))
        finalResult = input;
    }
    

    使用上述技术 finalResult null 如果输入无法解析为 true false .

        3
  •  -2
  •   Christophe Loeys    8 年前

    您可以用try-catch包围解析,并在catch上(因此,如果用户给出的不是true或false的内容),将输入设置为null。