我是一个C#初学者,将空字符串转换为double类型可以在button1_click
事件下进行...但是在Public Form1()
下进行会出现以下错误:
输入的字符串格式不正确。
这里是代码...(包括form1.cs和Guy.cs类)
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
guy1 = new Guy() ;
guy1.guyname = textBox1.Text;
guy1.guycash = double.Parse(textBox2.Text);
}
}
Guy guy1 ;
private void button1_Click(object sender, EventArgs e)
{
label5.Text = guy1.TakeCash(double.Parse(textBox3.Text)).ToString();
}
}
}
代码文件 Guy.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
class Guy
{
private string name;
private double cash;
public string guyname
{
get { return name; }
set { name = value; }
}
public double guycash
{
get { return cash ; }
set { cash = value; }
}
public double TakeCash(double amount)
{
if (cash > amount)
{
cash -= amount;
return cash;
}
else
{
MessageBox.Show("Not enough Cash.");
return 0;
}
}
}
}
错误是由于
guy1.guycash = double.Parse(textBox2.Text);
这一行引起的,当我在它之前的If()中尝试使用double.TryParse(textbox2.Text, out x)
时,它返回false。请问如何解决这个问题? 提前感谢。