C# Cannot implicitly convert type 'string' to 'bool' 错误

C# Cannot implicitly convert type 'string' to 'bool' error

我是 C# 的新手,我使用的是 Microsoft Visual Studio Express 2013 Windows 桌面版,我试图做一个测验,我在其中提出问题,用户必须回答是这样,这是代码,我得到的错误是 "Cannot implicitly convert type 'string' to 'bool'" 这发生在 2 个 if 语句上,我知道 bool 的值为 true 或 false 但它是一个字符串,所以为什么会给我这个错误?任何帮助都应该受到赞赏。 PS:我只包含了我遇到问题的那部分代码,这是主要 class[=13= 中唯一的代码]

代码如下:

 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;
        }

在你所有的 if 语句中

if (answer1 = "yes")

应该是

if (answer1 == "yes")

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

请看这一行:

if (answer1 = "yes") {

这会先将 "yes" 分配给 answer1,然后就像

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

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

你必须像这样进行比较:

if(answer1 == "yes") {

或者您可以像这样使用等号:

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

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

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

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

不过我更喜欢

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

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

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

有关 C# 中运算符的完整列表,请检查 this out. As an asside I would generally recommend againt using 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;
        }