[英]C# inheritance and Object reference
我是C#的新手,試圖弄清楚繼承是如何工作的。 我收到以下錯誤。 為什么父參數必須是靜態的?
嚴重性代碼說明項目文件行抑制狀態錯誤CS0120非靜態字段,方法或屬性'Rectangle.name'需要對象引用PurrS PATH \\ Sign.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;
}
}
}
您必須通過帶有更多參數的構造函數傳遞參數
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;
}
您看到的問題源於Rectangle
具有單個構造函數的事實-創建Rectangle
實例的唯一方法是將其傳遞給您的8個參數。
當您創建一個繼承自Rectangle
的Sign
(因為它是 Rectangle
,它需要能夠調用其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 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;
}
不必聲明您正在使用的任何字段,因為它們是從父類繼承的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.