【问题标题】:Why can't I inherit this variable?为什么我不能继承这个变量?
【发布时间】:2015-02-03 02:13:13
【问题描述】:

我收到此代码的一个错误:

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,但它们都产生相同的结果。

【问题讨论】:

  • 变量itemNo不存在,正确的变量是public Plant(int itemNumber, string description, decimal price, decimal size) : base(itemNumber, description, price)

标签: c# class protected derived-class


【解决方案1】:

当您在构造函数上调用base 时,这些变量甚至还不存在(基类尚未构造)。

因此,您不能在 base 构造函数调用中将类成员传递给它。相反,您需要:

public Plant(int itemNumber, string description, decimal price, decimal size) : 
    base(itemNumber, description, price)
{
}

这会将提供给Plant 的参数传递给基类,这正是您想要的。

【讨论】:

    【解决方案2】:
    public Plant(int itemNumber, string description, decimal price, decimal size)
                : base(itemNo, description, price)
            {
                this.Size = size;
            }
    

    当你在构造函数中使用它时,你还没有访问基类成员的权限,所以你得到了错误。

    【讨论】:

      【解决方案3】:

      您不能在构造函数中引用继承的属性。这样做:

      public Plant(int itemNumber, string description, decimal price, decimal size)
          : base(itemNumber, description, price)
      {
          this.Size = size;
      }
      

      【讨论】:

        猜你喜欢
        • 2016-07-30
        • 2010-09-28
        • 1970-01-01
        • 1970-01-01
        • 2010-10-20
        • 1970-01-01
        • 1970-01-01
        • 2018-09-04
        • 1970-01-01
        相关资源
        最近更新 更多