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

private void updateButton_Click(object sender, EventArgs e) { //custID.Text = customers[id].ID.ToString(); customers[id].Name = custName.Text.ToString(); customers[id].Suburb = custSuburb.Text.ToString(); customers[id].Balance = custBal.Text; customers[id].Year_used = custYear.Text; } } public class Customer { protected string id; protected string name; protected string suburb; protected double balance; protected double year_used; public string ID { get { return id; } } public string Name { get { return name; } set { value = name; } } public string Suburb { get { return suburb; } set { value = suburb; } } public double Balance { get { return balance; } set { value = balance; } } public double Year_used { get { return year_used; } set { value = year_used; } } public Customer(string id, string name, string suburb, double balance, double year_used) { this.id = id; this.name = name; this.suburb = suburb; this.balance = balance; this.year_used = year_used; } } 

似乎我在尝试运行代码时遇到此错误? 似乎是什么问题我改变了所有有int的东西。

以及:

  customers[id].Balance = custBal.Text; customers[id].Year_used = custYear.Text; 

什么是custBal的正确代码。 和custYear。 让它显示在我的表格上? 有任何想法吗?

您的用户正在输入余额并正在键入文本,那么您如何知道文本可以用数字表示? C#不允许你将字符串转换为双精度,因为没有对字符串做出实质性假设没有独特的方法,隐式转换应该永远不会抛出exception(框架设计指南),所以最好不提供隐式完全转换。

例如,因为它是一个余额,如果用户键入“(100.25)”或“-100.25”或“ – $ 100.25”或“ – €100,25”或“负一百二十五美分”,该怎么办?那些是有效的字符串,那么如何将它们转换为双精度?

答案是没有一个正确的答案:你可以用任何对你有意义的方式将字符串映射为double。 当然,您可以编写自己的Funcforms的函数,但.Net框架提供的函数实现了最常见和直观的转换。

其他人发布了double.Parsedouble.TryParse所以我想添加以确保在必要时也查看NumberStylesIFormatProvider

假设您知道它们包含格式正确的数字,您想要的是解析每个字符串中包含的数值并将其分配给double类型变量(这涉及将您的数字表示forms转换为另一个不同的二进制文件内容:一个双),而不是它(没有)。 尝试:

 customers[id].Balance = Double.Parse(custBal.Text); customers[id].Year_used = Double.Parse(custYear.Text); 

或者,如果要针对返回的布尔值测试解析的成功而不是执行exception处理以测试FormatException,则可以使用TryParse:

 if (!Double.TryParse(custBal.Text, customers[id].Balance)) Console.WriteLine("Parse Error on custBal.Text"); if (!Double.TryParse(custYear.Text, customers[id].Year_used)) Console.WriteLine("Parse Error on custYear.Text"); 

更多信息:

http://msdn.microsoft.com/en-us/library/t9ebt447%28v=vs.80%29.aspx

http://msdn.microsoft.com/en-us/library/994c0zb1.​​aspx

您不能直接将string分配给double 。 您需要解析字符串以将它们分配给双精度数,如下所示:

 customers[id].Balance = double.Parse(custBal.Text); customers[id].Year_used = double.Parse(custYear.Text); 

您应该使用Double.TryParse()将您的字符串转换为Double.You无法在Double数据类型上保存字符串,并且c#中没有可用的隐式转换来执行此操作

 Double result; Double.TryParse(custBal.Text,out result); 

将’String’转换为’Double’的最佳方法是使用TryParse,如下所示:

 int result; if (double.TryParse(custBal.Text, out result)) customers[id].Balance = result; if (double.TryParse(custYear.Text, out result)) customers[id].Year_used = result;