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

标签 c# class protected derived-class

这段代码出现一个错误:

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/

相关文章:

C# 动态/扩展对象的深度/嵌套/递归合并

java - 在 Java 中,如何让不同行中的两个类相互交互?

c++ - 静态类 C++

oop - 你应该使用 protected 成员变量吗?

c++ - 如何从派生类访问基类中的 protected 方法?

c# - 发送附件邮件 Windows phone 8 C sharp

c# - MySQL 连接器 NET 6.7.9 - 修复了 WinRT 程序集的 "common"问题

ios - Objective-C 从字符串中获取类属性

java - Java中基类中父类(super class)的 protected 方法会发生什么?

c# - AppDomain.CreateInstanceAndUnwrap 可以返回 null 吗?