为什么我不能继承这个变量
本文关键字:变量 继承 不能 为什么 | 更新日期: 2023-09-27 18:33:14
我收到以下代码的一个错误:
An object reference is required for the non-static field, method, or property
我正在尝试从派生类继承 itemNo 变量以将其放入构造函数中,但由于某种原因它不接受它。
完整代码:
public class InvItem
{
protected int itemNo;
protected string description;
protected decimal price;
public InvItem()
{
}
public InvItem(int itemNo, string description, decimal price)
{
this.itemNo = itemNo;
this.description = description;
this.price = price;
}
public int ItemNo
{
get
{
return itemNo;
}
set
{
itemNo = value;
}
}
public string Description
{
get
{
return description;
}
set
{
description = value;
}
}
public decimal Price
{
get
{
return price;
}
set
{
price = value;
}
}
public virtual string GetDisplayText(string sep)
{
return itemNo + sep + description + " (" + price.ToString("c") + ")";
}
}
public class Plant : InvItem
{
private decimal size;
public Plant()
{
}
public Plant(int itemNumber, string description, decimal price, decimal size) : base(itemNo, description, price)
{
this.Size = size;
}
public decimal Size
{
get
{
return size;
}
set
{
size = value;
}
}
public override string GetDisplayText(string sep)
{
return base.GetDisplayText(sep) + " (" + size + ")";
}
}
它发生在带有参数的 Plant 类构造函数中。我尝试将其设置为公共、私有和受保护,但它们都产生相同的结果。
当你在构造函数上调用base
时,这些变量甚至还不存在(基类尚未构造)。
因此,不能在 base
构造函数调用中将类成员传递给它。相反,您需要:
public Plant(int itemNumber, string description, decimal price, decimal size) :
base(itemNumber, description, price)
{
}
这会将提供给Plant
的参数传递给基类,这是您想要的。
public Plant(int itemNumber, string description, decimal price, decimal size)
: base(itemNo, description, price)
{
this.Size = size;
}
当您在构造函数中使用它时,您还无法访问基类成员,因此您会收到错误。
不能在构造函数中引用继承的属性。 这样做:
public Plant(int itemNumber, string description, decimal price, decimal size)
: base(itemNumber, description, price)
{
this.Size = size;
}