在 C# 中,如何将键盘输入的 null 输入到可为 null 类型的布尔变量中?

In C#, how to take null input from keyboard into nullable type boolean variable?

我想做这样的事情-

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");
        }
    }

}

这里如果用户没有给出答案而只是简单地按下回车,变量输入必须存储值null并且输出必须是No answer given.

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

但是如果没有给出输入并按下回车,编译器会抛出异常

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

那么如何获取存储在变量 input 中的 null 值,以便输出为 No answer given

这里,

问题

显然不是重复的,因为它不想直接从键盘获取空输入。如果不能接受这样的输入,可空类型的效用是什么,因为也有变通办法?

您可以用 try-catch 围绕您的解析,并在捕获时(因此如果用户给出的不是 true 或 false 的东西)将输入设置为 null。

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
bool? finalResult = null;
bool input = false;

Console.WriteLine("Are you Major?");

if (bool.TryParse(Console.ReadLine(), out input))
    finalResult = input;
}

如果输入无法解析为 truefalse.

,则使用上述技术 finalResult 将是 null