2017-10-04 135 views
-1

我想從基類繼承,但我得到一個我找不到的錯誤。這是基類:C#基礎構造函數繼承

class Item 
{ 
    protected string name; 

    public Item(string name) 
    { 
     this.name = name; 
    } 
} 

這是繼承的類:

class ItemToBuy : Item 
{ 
    private int lowPrice; 
    private int highPrice; 
    private int maxQuantity; 

    public ItemToBuy(int lowPrice, int highPrice, int maxQuantity) : base(name) 
    { 
     this.lowPrice = lowPrice; 
     this.highPrice = highPrice; 
     this.maxQuantity = maxQuantity; 
    } 
} 

的問題是這一行:

public ItemToBuy(int lowPrice, int highPrice, int maxQuantity) : base(name)

其中 '名' 是強調與錯誤消息「非靜態字段,方法或屬性'Item.name'需要對象引用,如果用字符串文字替換它,錯誤消息不存在。 ng繼承構造函數?

+1

如果你沒有在ItemToBuy的構造函數的參數名稱,不能調用基類的,需要一個名稱的構造參數。如果你沒有它,那麼向不帶參數的基類添加一個構造函數,或者改變你的ItemToBuy構造函數來需要一個名稱參數傳遞給基類 – Steve

+1

好吧,那麼考慮一下這個問題。基類需要一個'name'。因此,任何派生類都需要將'name'傳遞給基類構造函數。它不能簡單地將它變出 - 無論是派生類以某種方式創建一個'name'並將其傳遞給基類的構造函數,或者'name'必須是派生類的構造函數的參數,然後傳遞通過基類的構造函數。 –

+1

[C#「非靜態字段,方法或屬性需要對象引用」](https://stackoverflow.com/questions/4817967/c-sharp-an-object-reference-is-必需的非靜態字段方法或公關) – Sinatr

回答

2

您需要在ItemToBuy類的構造函數太

public ItemToBuy(string name ,int lowPrice, int highPrice, int maxQuantity) : base(name) 
0
public ItemToBuy(int lowPrice, int highPrice, int maxQuantity) : base(name) 
{ 
    this.lowPrice = lowPrice; 
    this.highPrice = highPrice; 
    this.maxQuantity = maxQuantity; 
} 

應改爲有名稱:

public ItemToBuy(int lowPrice, int highPrice, int maxQuantity, string name) : base(name) 
{ 
    this.lowPrice = lowPrice; 
    this.highPrice = highPrice; 
    this.maxQuantity = maxQuantity; 
} 

你需要指定在該name參數構造函數,根據我上面的代碼。

+0

在文體上,我會把名稱參數首先放在ItemToBuy構造函數中。 – Polyfun

+0

這將取決於上下文是否有意義,但yep @Polyfun肯定是有效的。 'name'可以在任何位置(不一定是第一個或最後一個)。 – mjwills

3

您的ItemToBuy類沒有任何「名稱」知識。 您構建構造函數的方式,「名稱」需要是一個定義的字符串。

比方說,你的構造是這樣的:

class ItemToBuy : Item 
{ 
    private int lowPrice; 
    private int highPrice; 
    private int maxQuantity; 

    public ItemToBuy(int lowPrice, int highPrice, int maxQuantity, string name) : base(name) 
    { 
     this.lowPrice = lowPrice; 
     this.highPrice = highPrice; 
     this.maxQuantity = maxQuantity; 
    } 
} 

這將工作,因爲名稱參數定義。

所以,你要麼像那樣做,要麼傳遞一個硬編碼的值,就像你做的那樣。

+0

Upvoted,因爲這是實際解釋問題的唯一答案。 –

0

你需要在ItemToBuy的構造函數接受的名字:

public ItemToBuy(int lowPrice, int highPrice, int maxQuantity,string name) : base(name)