我想做这样的事情-
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
。
在我的代码中,输入true
和false
工作正常。
但是如果没有给出输入并按下回车,编译器会抛出异常
System.FormatExeption has been thrown
String was not recognized as a valid Boolean
那么如何获取null
存储在变量中的值input
以便输出为No answer given
这里,
显然不是重复的,因为它不想直接从键盘获取空输入。如果不能采用这样的输入,那么可空类型的用途是什么,因为也有解决方法?