繁体   English   中英

如何使用 if-else 语句在 c# 中修复此隐式转换错误?

[英]How to fix this implicitly convert error in c# with if-else statement?

你能帮我解决这个问题吗? 我在我的代码中收到此错误:

无法将类型“bool”隐式转换为“string”

我在互联网上搜索以解决此问题,但看到计算器溢出问题仍未解决。 代码是

using System;

namespace MyApplication
{
  class Program
  {
    static void Main(string[] args)
    {
      Console.WriteLine("How are you?");
      
      string choice = bool.Parse(Console.ReadLine()); //Error in this line
      
      if (choice == "Fine" || choice == "Good" || choice == "doing well")
      {
        Console.WriteLine("It's great to know that you're" + choice);
      }
      
      else if (choice == "bad" || choice == "not good" || choice == "not so well")
      {
        Console.WriteLine("What happened? Why" + choice + "?");
      }
            
    }
  }
}

stackoverflow 中的一个问题建议我在ReadLine之前使用bool.Parsebool.TryParse 如此使用但仍然错误。

不要这样做。

string choice = bool.Parse(Console.ReadLine());

在这里似乎没有必要将string转换为bool ,再转换回string

您显然是在将输入中的string与选项进行比较。

if (choice == "Fine" || choice == "Good" || choice == "doing well")

Choice 只需要是一个string ,这里不需要bool ..

而不是仅仅使用string

string choice = Console.ReadLine();

if (choice == "Fine" || choice == "Good" || choice == "doing well")

如果有人输入了“true”或“false”,并且您想将该字符串输入转换为bool ,您将使用bool.Parse

将逻辑值的指定范围表示形式转换为其等效的布尔值。

暂无
暂无

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

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