2011-05-30 23 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