我正在制作一個簡單的 C# 控制臺應用程式,用戶必須輸入 1 或 2 才能選擇他們的選項,顯然,由于用戶可以輸入任何內容,我需要進行檢查以回傳他們的輸入,如果它是'不是 1 或 2,它將回傳 null。
這是我做的
bool? getResponse = null;
if (read == "1")
{
getResponse = true;
}
else if (read == "2")
{
getResponse = false;
}
else
{
getResponse = null;
}
了解 C#,肯定有一種方法可以簡化這一點,但我似乎無法找到一種在線方式。任何指標?
uj5u.com熱心網友回復:
可能您正在尋找條件運算子?:。
但是,如果邏輯變得復雜(添加邏輯等),這可能會很復雜,難以閱讀。read == "3"
getResponse = read == "1"
? true
: read == "2"
? true
: null;
您可以應用的另一種方法是C# 9 的 switch 運算式。
getResponse = read switch
{
"1" => true,
"2" => false,
_ => null,
};
第三種方法是使用Dictionary.
using System.Collections.Generic;
using System.Linq;
Dictionary<string, bool> resultDict = new Dictionary<string, bool>
{
{ "1", true },
{ "2", false }
};
getResponse = resultDict.TryGetValue(read, out bool _result)
? _result
: null;
uj5u.com熱心網友回復:
您可以在這樣的情況下使用三元運算子
string read = Console.ReadLine();
bool? response = read == "1" ? true
: read == "2" ? false : null;
但最好只有兩種可能的方法,因為你可以看到它很容易失控。在這種情況下,我上面的代碼沒問題,但如果你有 10 種可能性,也許這樣的方法是個好方法
// lets say there is ways
// 1 = true, 2 = false, 3 = null
// and any other input means exception
string read = Console.ReadLine()!;
Dictionary<string, bool?> keyValues = new();
keyValues.Add("1", true);
keyValues.Add("2", false);
keyValues.Add("3", null);
bool? response = keyValues.ContainsKey(read) ? keyValues[read]
: throw new Exception();
這里的例外只是舉例,我的觀點是,當你有多種可能性時,用字典做這樣的事情似乎比 if/else、switch/case 或多條件三元運算子干凈得多
uj5u.com熱心網友回復:
我認為這很不可讀,但它避免了嵌套的三元組。
getResponse = int.TryParse(read, out var i) && i > 0 && i < 3 ? (bool)(2-i) : null;
將 決議string為int,確保它是有效范圍,然后進行一些數學運算,以便將其轉換為bool。將整數型別轉換為 abool時,0 表示false,非零表示true。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/449945.html
