簡體   English   中英

在 C# 中,如何將鍵盤的空輸入轉換為可空類型的布爾變量?

[英]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

在我的代碼,輸入truefalse工作正常。

但是如果沒有輸入並按下回車,編譯器會拋出異常

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

那么如何獲取存儲在變量input null值,以便輸出為No answer given

這里,

問題字符串未被識別為有效的布爾值 C#

顯然不是重復的,因為它不想直接從鍵盤獲取空輸入。 如果不能接受這樣的輸入,那么可空類型的效用是什么,因為也有解決方法?

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

你可以用 try-catch 包圍你的解析,並在 catch 上(所以如果用戶給出非真或假的東西)將輸入設置為空。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM