[英]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.Parse
或bool.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.