2016-02-29 65 views
1

我是C#的新手,並試圖弄清楚繼承是如何工作的。我收到以下錯誤。爲什麼父參數必須是靜態的?C#繼承和對象引用

嚴重性代碼說明項目文件的線路抑制狀態 錯誤CS0120的對象引用需要非靜態字段, 方法或屬性「Rectangle.name」咕嚕咕嚕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; 

    } 
} 
} 

回答

1

你看到的問題源於這樣的事實:Rectangle有一個構造函數 - 創建Rectangle實例的唯一方法是傳遞它的8個參數。

當你創建一個SignRectangle繼承 - 因爲它一個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) 

例如。

1

您需要在此展開:

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; 
} 
1

必須要麼使用一些更多的參數從構造函數傳遞參數

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; 

     } 
+0

在這裏我想參數會自動傳遞給父類。謝謝。 – Theletos

0

繼承意味着您的子類(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; 
    } 

而不必聲明您使用的任何字段,因爲它們是從父類繼承的。