gpt4 book ai didi

c# - 为什么我不能继承这个变量?

转载 作者:行者123 更新时间:2023-11-30 22:01:56 24 4
gpt4 key购买 nike

这段代码有一个错误:

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com