C# 提示输入 boolean 值

标签 c# boolean

我的搜索结果为空,或者我只是不明白我找到的结果。我试图提示用户输入一个 boolean 值,但我希望答案是"is"或“否”。如果您需要查看更多代码,请告诉我,但我有这个作为提示。

public static bool getBoolInputValue(string inputType)
    {
        bool valid = false;
        bool value = true;
        string inputString = string.Empty;
        do
        {
            inputString = GetInput(inputType);
            if (!(String.IsNullOrEmpty(inputString)))
            {
                valid = bool.TryParse(inputString, out value);
            }
            if (!valid)
                Console.WriteLine("Invalid " + inputType + " try again!");
        } while (!valid);

        return value;
    }

这是我的 boolean 值的参数。也许这需要更具体?

public bool Nitrus
    {
        set { nitrus = value; }
        get { return nitrus; }
    }

谢谢你的帮助。我对编程相当陌生,但无法弄清楚这一点。它确实提示成功,但无论我在框中输入什么答案,它都会告诉我这不是正确的格式。

最佳答案

如果我理解正确,您希望用户输入“yes”,这意味着您有一个 True 值。如果这是正确的,请跳过所有 string.IsNullOrEmptybool.TryParse 内容并执行类似这样的操作。

//make it ToLower so that it will still match if the user inputs "yEs"
inputString = GetInput(inputType);
if (inputString.ToLower() == "yes")
{
  value = true;
}
else
{
  value = false;
}

//note that the if/else code is the same as directly applying 
// the value from the comparison itself:
// value = inputString.ToLower() == "yes";

// this allows the user to type in "yes" or "y":
// value = inputString.ToLower() == "yes" || inputString.ToLower() == "y";

关于C# 提示输入 boolean 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9354152/

相关文章:

c# - MVC4 表单验证 - 自定义 html 消息 howto?

C# 字符串等于不能正常工作

c# - 强制转换 : (A) x and x as A? 之间有什么区别

c# - 如何将字节数组(SQL 服务器时间戳)转换为日期时间(C#)?

javascript - 将 boolean 结果转换为数字/整数

java - 确定范围是否重叠

c# - 如何在 VS 2015 RC 中将控制台应用程序(.NET 核心 5)发布为单个 EXE 文件?

c# - boolean 值是什么? isActive = false 在 C# 中是什么意思?

c - 确保用户的输入与我的程序生成的字符相匹配

python-3.x - boolean 测试 : Python prints '1' or 'True'