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

可能重复:
帮助转换类型 – 不能隐式地将类型’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; } 

并得到以下错误:

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

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

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

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

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

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

 Price = double.Parse(Console.ReadLine()); Food =bool.Parse(Console.ReadLine()); count = int.Parse(Console.ReadLine()); 

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

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

或者(Mr-Mr-Happy)

  Food = answer == "y" 

您需要在计算finalprice指定显式finalprice

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

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

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

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

 Console.Write("Unit price: "); double.TryParse(Console.ReadLine(), out Price); Console.Write("Food item y/n: "); bool.TryParse(Console.ReadLine(), out Food); Console.Write("Count: "); int.TryParse(Console.ReadLine(), out count); 
 private double Price; private bool Food; private int count; private decimal finalprice; public void Readinput() { Console.Write("Unit price: "); double.TryParse(Console.ReadLine(), out Price); Console.Write("Food item y/n: "); bool.TryParse(Console.ReadLine(), out Food); Console.Write("Count: "); int.TryParse(Console.ReadLine(), out count); } private void calculateValues() { finalprice = Price * count; } 

您必须在适当的解析器函数中包装Console.ReadLine()调用,因为(例如,与PHP不同)C#是一种静态类型语言,另外只能保证安全和无损的转换可以隐式完成:

 Price = double.Parse(Console.ReadLine()); Console.Write("Food item y/n: "); // I think you want the user to type in "y", "Y", "n" or "N", right? Food = Console.ReadLine().ToUpper() == "Y"; Console.Write("Count: "); count = int.Parse(Console.ReadLine()); 

在计算方法中,您必须将结果double显式转换为小数,因为C#不支持固定点和浮点值之间的隐式转换:

 finalprice = (decimal)(Price * count);