c#不能隐式转换类型'string'& # 39; bool # 39;错误

本文关键字:bool 错误 转换 string 不能 类型 | 更新日期: 2023-09-27 18:02:31

我是c#的新手,我正在使用微软Visual Studio Express 2013 Windows桌面版,我试图做一个测验,我问的问题,用户必须回答它,所以,这是代码,我得到的错误是"不能隐式转换类型'字符串'到'bool'",这发生在2个if语句,我知道,一个bool值为真或假,但它是一个字符串,所以为什么它给我这个错误?任何帮助都值得感激。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'& # 39; bool # 39;错误

所有if语句

if (answer1 = "yes")
应该

if (answer1 == "yes")
c#中的

=用于赋值,==用于比较。在所有if语句中更改它,就可以了

请看这一行:

if (answer1 = "yes") {

这将首先为answer1分配"yes"然后像

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

那么现在这将尝试将answer1转换为一个布尔值,这是if语句所要求的。这不起作用,并抛出异常。

你必须做这样的比较:

if(answer1 == "yes") {

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

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

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

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

但是我更喜欢

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

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

这个=是c#中的赋值操作符
这个==是c#中的比较操作符

查看c#中操作符的完整列表。顺便说一句,我一般不建议使用goto语句

你的代码应该看起来像这样。

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