C# C无法将类型“string”隐式转换为“bool”错误

C# C无法将类型“string”隐式转换为“bool”错误,c#,string,console,boolean,C#,String,Console,Boolean,我是C新手,我正在使用microsoft Visual Studio Express 2013 Windows桌面版,我试图做一个测验,在测验中我问了问题,用户必须回答,所以,下面是代码,我得到的错误是 无法将类型“string”隐式转换为“bool”,这种情况发生在2 if语句上,我知道bool的值为true或false,但它是一个字符串,为什么它会给我这个错误?任何帮助都应该感谢。 PS:我只包含了我遇到问题的部分代码,这是主类中唯一的代码 代码如下: Start: Con

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

在你所有的if语句中

if (answer1 = "yes")
应该是

if (answer1 == "yes")

在c中,=用于赋值,==用于比较。在所有if语句中更改它,您就会没事了

请看这一行:

if (answer1 = "yes") {
这将首先为答案1指定yes,然后它就像

if(answer1) { // answer1 = "yes"
现在,这将尝试将answer1(字符串)转换为布尔值,这是if语句所需要的。这不起作用并引发异常

您必须进行如下比较:

if(answer1 == "yes") {
if("yes".Equals(answer1)) {
或者你可以用这样的等式:

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

然后对else if执行相同的操作。

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

   if (answer1 == "yes") {
     ...
   }
不过我更喜欢

  if (String.Equals(answer1, "yes", StringComparison.OrdinalIgnoreCase)) {
    ...
  }
如果用户选择Yes或Yes等作为答案,

=是C中的赋值运算符 ==是C中的比较运算符 有关C中运算符的完整列表,请查看。作为一个助手,我通常建议不要使用 所有这些都表明您的代码应该是这样的

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

你必须输入==not==assigns,==comparableduplicate of我认为回答一个重复的问题是不好的。或者至少有一个答案是不够的,请不要像下面Terrance提到的那样使用goto语句。它们对环境和小动物有害多谢mate和其他人,解决了这个问题