这段代码出现一个错误:
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 类构造函数中。我尝试过将其设置为公共(public)、私有(private)和 protected ,但它们都会产生相同的结果。
最佳答案
当您在构造函数上调用 base
时,这些变量甚至还不存在(基类尚未构造)。
因此,您无法在 base
构造函数调用中将类成员传递给它。相反,您需要:
public Plant(int itemNumber, string description, decimal price, decimal size) :
base(itemNumber, description, price)
{
}
这会将提供给 Plant
的参数传递给基类,这就是您想要的。
关于c# - 为什么我不能继承这个变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27306899/