有没有办法将返回可空布尔值的检查压缩为 1-2 行?

0 c# simplify

我正在制作一个简单的 C# 控制台应用程序,用户必须输入 1 或 2 来选择他们的选项,显然,由于用户可以输入任何内容,我需要进行检查以返回他们的输入,如果不是如果不是 1 或 2,它将返回 null。

这是我做的

bool? getResponse = null;
if (read == "1")
{
    getResponse = true;
}
else if (read == "2")
{
    getResponse = false;
}
else
{
    getResponse = null;
}
Run Code Online (Sandbox Code Playgroud)

了解 C#,肯定有一种方法可以简化此操作,但我似乎找不到在线方法。有什么指点吗?

Yon*_*hun 5

也许您正在寻找条件运算符?:

但如果逻辑变得复杂(添加逻辑等) ,维护起来可能会很复杂并且难以阅读。read == "3"

getResponse = read == "1" 
    ? true 
    : read == "2" 
        ? false 
        : null;
Run Code Online (Sandbox Code Playgroud)

您可以应用的另一种方法是C# 9 的 switch 表达式

getResponse = read switch
{
    "1" => true,
    "2" => false,
    _ => null,
};
Run Code Online (Sandbox Code Playgroud)

第三种方法是使用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;
Run Code Online (Sandbox Code Playgroud)