[英]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");
}
}
}
在這里,如果用戶沒有給出答案並簡單地按回車鍵,則變量 input 必須存儲值null
並且 output 必須為No answer given
。
在我的代碼,輸入true
和false
工作正常。
但是如果沒有輸入並按下回車,編譯器會拋出異常
System.FormatExeption has been thrown
String was not recognized as a valid Boolean
那么如何獲取存儲在變量input
null
值,以便輸出為No answer given
這里,
顯然不是重復的,因為它不想直接從鍵盤獲取空輸入。 如果不能接受這樣的輸入,那么可空類型的效用是什么,因為也有解決方法?
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;
}
如果輸入無法解析為true
或false
則使用上述技術finalResult
將為null
。
你可以用 try-catch 包圍你的解析,並在 catch 上(所以如果用戶給出非真或假的東西)將輸入設置為空。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.