2011-05-30 24 views
0

我试图编写简单的成员资格类。第一个类名是Customer,它具有其他类,如继承自Customer类的Silver_Customer,Gold_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”;行给我NullReferenceException错误,但是customer.Name =“标记1”行工作。

+0

您能向我们展示Customer,Standard_Customer类的定义吗? – tomfanning 2011-05-30 19:10:22

+0

请参阅http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-in-net – 2011-05-30 19:10:54

回答

1

btnCustomer_Click中,您未设置全局customer对象。您正在设置它的本地版本。更改您的代码,如下所示:

private void btnCustomer_Click(object sender, EventArgs e) 
{ 
    customer = new Standard_Customer(txtName.Text, txtSurname.Text, 0); 
+0

这并不能解释他所看到的空引用异常。 – tomfanning 2011-05-30 19:12:23

+0

@tomf:是的,它的确如此。 'customer'对象从未设置,因为改为设置了一个完全不同的名为'customer'的对象。 – 2011-05-30 19:13:38

+0

你是对的,我错误地认为在btnCustomer_Click发生异常。 – tomfanning 2011-05-30 20:51:17

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