C# 继承和对象引用

本文关键字:对象引用 继承 | 更新日期: 2023-09-27 18:36:43

我是C#的新手,试图弄清楚继承是如何工作的。我收到以下错误。为什么父参数必须是静态的?

严重性代码说明项目文件行抑制状态 错误 CS0120 非静态字段需要对象引用, 方法或属性 'Rectangle.name' PurrS 路径''符号.cs 15 活动

父母:

namespace PurrS.Maps
{
public class Rectangle
{
    protected string name;
    protected int id;
    protected float a;
    protected float b;
    protected float c;
    protected float d;
    protected int posX;
    protected int posY;
    //A----B
    //|    | 
    //C----D
    public Rectangle(string name, int id, float a, float b, float c, float d, int posX, int posY)
    {
        this.name = name;
        this.id = id;
        this.a = a;
        this.b = b;
        this.c = c;
        this.d = d;
    }
}
}

孩子:

namespace PurrS.Maps
{
public class Sign : Rectangle
{
    string message;
    public Sign(string message) 
        : base(name, id, a, b, c, d, posX, posY) { //This is where it fails.
        this.message = message;
    }
}
}

C# 继承和对象引用

您看到的问题源于Rectangle只有一个构造函数的事实 - 创建Rectangle实例的唯一方法是将 8 个参数传递给它。

当您创建继承自RectangleSign时 - 因为它是一个Rectangle - 它需要能够调用其Rectangle构造函数才能成功构造自身。

因此,在调用构造

函数时,它需要所有可用于在Rectangle上调用构造函数的参数(您只有一个)。

您可以在 Sign 中请求参数,也可以在 Sign 构造函数中对它们进行硬编码:

 public Sign(string message, string name, int id, float a, float b, float c, float d, int posX, int posY) 
     :base(name,id,a,b,c,d,posX,poxY)
 public Sign(string message) : base("a name", 1, 1, 2, 3, 4, 10, 10)

例如。

您必须使用更多参数从构造函数传递参数

public Sign(string name, int id, float a, float b, float c, float d, int posX, int posY, string message)
                : base(name, id, a, b, c, d, posX, posY)
            { //This is where it fails.
                this.message = message;
            }

或提供一些默认的固定值:

        public Sign(string message)
            : base("foo", 1, 0, 0, 0, 0, 1, 1)
        { //This is where it fails.
            this.message = message;
        }

你需要对此进行扩展:

public Sign(string message) 
    : base(name, id, a, b, c, d, posX, posY) { //This is where it fails.
    this.message = message;
}

将参数传递给基类,如下所示:

public Sign(string message, string name, int id, etc...) 
    : base(name, id, a, b, c, d, posX, posY) { 
    this.message = message;
}

> 继承意味着子类(Sign 类)将具有父类中的所有字段和方法。因此,你可以说

public Sign(string name, int id, float a, float b, float c, float d, int posX, int posY)
    {
        this.name = name;
        this.id = id;
        this.a = a;
        this.b = b;
        this.c = c;
        this.d = d;
    }

并且不必声明正在使用的任何字段,因为它们是从父类继承的。