C#基础构造函数继承

问题描述:

我想从基类继承,但我得到一个我找不到的错误。这是基类: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://*.com/questions/4817967/c-sharp-an-object-reference-is-必需的非静态字段方法或公关) – Sinatr

您需要在ItemToBuy类的构造函数太

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

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

您的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,因为这是实际解释问题的唯一答案。 –

你需要在ItemToBuy的构造函数接受的名字:

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