繁体   English   中英

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

[英]C# Cannot implicitly convert type 'string' to 'bool' error

我是C#的新手,我使用的是Microsoft Visual Studio Express 2013 Windows桌面版,我试图做一个测验,问一个问题,用户必须回答这个问题,这是代码,我得到的错误是“无法将类型'string'隐式转换为'bool'”,这在2条if语句中发生,我知道布尔值要么为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") {

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

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

因此,现在它将尝试将if1语句要求的字符串形式的answer1转换为布尔值。 这不起作用,并引发异常。

您必须进行如下比较:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM