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

use*_*722 9 c#

可能重复:
帮助转换类型 - 无法将类型'string'隐式转换为'bool'

我有这个代码:

private double Price;
private bool Food;
private int count;
private decimal finalprice;

public void Readinput()
{
    Console.Write("Unit price:  ");
    Price = Console.ReadLine();

    Console.Write("Food item y/n:  ");
    Food = Console.ReadLine();

    Console.Write("Count:  ");
    count = Console.ReadLine();
}

private void calculateValues()
{
    finalprice = Price * count;
}
Run Code Online (Sandbox Code Playgroud)

并得到以下错误:

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

无法将类型'string'隐式转换为'double'

无法将类型'string'隐式转换为'int'

无法将类型'double'隐式转换为'decimal'.存在显式转换(您是否错过了演员?)

我知道这意味着什么,但我不知道如何解决它.

ada*_*ost 18

使用bool.Parsebool.TryParse方法将字符串值转换为boolean.

Price = double.Parse(Console.ReadLine());
Food =bool.Parse(Console.ReadLine());
count = int.Parse(Console.ReadLine());
Run Code Online (Sandbox Code Playgroud)

您不能将"y"或"n"值转换为布尔值,而是必须以字符串形式接收值,如果是"y",则存储true,false否则.

Console.Write("Food item y/n:  ");
string answer = Console.ReadLine();
if(answer=="y")
   Food=true;
else
   Food=false;
Run Code Online (Sandbox Code Playgroud)

或者(Mr-Mr-Happy)

 Food = answer == "y"
Run Code Online (Sandbox Code Playgroud)

您需要在计算时指定显式强制转换finalprice.

private void calculateValues()
{
   // convert double result into decimal.
    finalprice =(decimal) Price * count;
}
Run Code Online (Sandbox Code Playgroud)


Bla*_*ear 5

您必须使用静态类Convert将您从控制台读取的内容(字符串)转换为实际类型.例如:

Console.Write("Count:  ");
count = Convert.ToInt32(Console.ReadLine());
Run Code Online (Sandbox Code Playgroud)

如果给出的参数无法转换,则会崩溃,但现在这不是您的主要问题,所以让我们保持简单.