我正在尝试编写简单的成员资格类。第一类名称是Customer,它有其他类,如Silver_Customer,Gold_Customer,它们继承自Customer类。
我在简单的Windows应用程序中使用这些类:
public Customer customer;
public Form_MURAT_TURAN()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
Product p1 = new Product("Blouse", 152.80);
Product p2 = new Product("T-Shirt", 50.25);
.....
lbProducts.Items.Add(p1);
lbProducts.Items.Add(p2);
.....
}
private void btnCustomer_Click(object sender, EventArgs e)
{
Customer customer = new Standard_Customer(txtName.Text, txtSurname.Text, 0);
customer.Name = "Mark 1";
customer.TotalAmount = 5;
gbCustomer.Enabled = false;
gbProduct.Enabled = true;
set_info(customer.customerType(), customer.Name + " " + customer.Surname, customer.TotalAmount);
}
private void btnAddToBasket_Click(object sender, EventArgs e)
{
customer.Name = "Mark 2";
}
除了btnAddToBasket_Click方法之外,一切正常。 customer.Name =“Mark 2”; line给我NullReferenceException
错误,但customer.Name =“Mark 1”行有效。
答案 0 :(得分:2)
你为什么不试试:
private void btnCustomer_Click(object sender, EventArgs e)
{
this.customer = new Standard_Customer(txtName.Text, txtSurname.Text, 0);
customer.Name = "Mark 1";
customer.TotalAmount = 5;
gbCustomer.Enabled = false;
gbProduct.Enabled = true;
set_info(customer.customerType(), customer.Name + " " + customer.Surname, customer.TotalAmount);
}
在创建新客户时尝试使用this.customer
。
答案 1 :(得分:1)
在btnCustomer_Click
中,您没有设置全局customer
对象。您正在设置它的本地版本。按如下方式更改您的代码:
private void btnCustomer_Click(object sender, EventArgs e)
{
customer = new Standard_Customer(txtName.Text, txtSurname.Text, 0);