【问题标题】:C# Cannot implicitly convert type 'string' to 'bool' errorC# 无法将类型“字符串”隐式转换为“布尔”错误
【发布时间】:2015-10-03 03:14:52
【问题描述】:

我是 C# 新手,我正在使用 microsoft Visual Studio Express 2013 Windows 桌面版,我正在尝试做一个测验,在其中我提出问题并且用户必须回答,所以这里是代码和错误我得到的是 “无法将类型'string'隐式转换为'bool'”,这发生在2个if语句上,我知道bool的值为true或false,但它是一个字符串,为什么它会给我这个错误?任何帮助都应该不胜感激。 PS:我只包含了我遇到问题的部分代码,这是主类中唯一的代码

代码如下:

 Start:
        Console.WriteLine();
        Console.WriteLine();
        Console.WriteLine("Question 1: Test? type yes or no: ");
        String answer1 = Console.ReadLine();

        if (answer1 = "yes") {
            Console.WriteLine();
            Console.WriteLine("Question 2: Test? type Yes or no");
        }
        else if (answer1 = "no")
        {
            Console.WriteLine();
            Console.WriteLine("Wrong, restarting program");
            goto Start;
        }
        else {
            Console.WriteLine();
            Console.WriteLine("Error");
            goto Start;
        }

【问题讨论】:

标签: c# string console boolean


【解决方案1】:

在你所有的 if 语句中

if (answer1 = "yes")

应该是

if (answer1 == "yes")

在c#中,=是赋值,==是比较。在你所有的 if 语句中改变它,你会没事的

【讨论】:

  • 感谢队友和其他所有人,:),解决了问题
【解决方案2】:

请看看这一行:

if (answer1 = "yes") {

这将首先将“是”分配给 answer1,然后就像

if(answer1) { // answer1 = "yes"

所以现在这将尝试将作为字符串的 answer1 转换为 if 语句所需的布尔值。这不起作用并引发异常。

您必须像这样进行比较:

if(answer1 == "yes") {

或者你可以像这样使用equals:

if("yes".Equals(answer1)) {

然后对 else if 做同样的事情。

【讨论】:

    【解决方案3】:

    直接原因是= 分配,而不是像== 那样比较值。 所以你可以做

       if (answer1 == "yes") {
         ...
       }
    

    不过我更喜欢

      if (String.Equals(answer1, "yes", StringComparison.OrdinalIgnoreCase)) {
        ...
      }
    

    如果用户选择"Yes""YES" 等作为答案

    【讨论】:

      【解决方案4】:

      this = 是 C# 中的赋值运算符
      this == 是 C# 中的比较运算符

      有关 C# 中运算符的完整列表,请查看this out。顺便说一句,我通常会建议再次使用 goto statements

      话虽如此,您的代码应该看起来像这样。

      Start:
              Console.WriteLine();
              Console.WriteLine();
              Console.WriteLine("Question 1: Test? type yes or no: ");
              String answer1 = Console.ReadLine();
      
              if (answer1 == "yes")
              {
                  Console.WriteLine();
                  Console.WriteLine("Question 2: Test? type Yes or no");
              }
              else if (answer1 == "no")
              {
                  Console.WriteLine();
                  Console.WriteLine("Wrong, restarting program");
                  goto Start;
              }
              else
              {
                  Console.WriteLine();
                  Console.WriteLine("Error");
                  goto Start;
              }

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-01-22
        • 2014-05-11
        • 1970-01-01
        • 1970-01-01
        • 2014-01-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多