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

问题描述 投票:-5回答:3

我想做这样的事情 -

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的输入工作正常。

但是如果没有给出输入并且按下了enter,则编译器会抛出异常

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

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

这里,

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

显然不是重复,因为它不想直接从键盘输入空值。如果不能采取这样的输入,可空类型的效用是什么,因为也会有解决方法?

c# exception boolean nullable keyboard-input
3个回答
2
投票
bool? finalResult = null;
bool input = false;

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

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

如果输入不能被解析为finalResultnull,使用上述技术true将是false


4
投票
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
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.