2012-12-26 27 views
1

我是從一個無參數的構造函數類這樣一個派生類:如何獲得基類的「新」參數?

public class Base 
{ 
    public Base(Panel panel1) 
    { 

    } 
} 

public class Derived : Base 
{ 
    public Derived() : base(new Panel()) 
    { 
     //How do I use panel1 here? 
    } 
} 

我怎麼能指在推導PANEL1?

(簡單的變通方法的歡迎。)

回答

4

Adil的回答假設你可以修改Base。如果你不能,你可以這樣做:

public class Derived : Base 
{ 
    private Panel _panel; 

    public Derived() : this(new Panel()) {} 

    private Derived(Panel panel1) : base(panel1) 
    { 
     _panel = panel1; 
    } 
} 
+1

好的。我實際上不能修改'Base'! – ispiro

+0

@ispiro注意私人_panel字段實際上有點危險。如果您在寫「如何在此處使用panel1」時記住面板的其他用途,則應該這樣做,然後刪除專用字段(當然還有分配)。並感謝您清理代碼格式! – phoog

+0

這正是我所做的(沒有私人領域)。但是,你的意思是「危險的」? – ispiro

1

您需要Base定義Panel,您可以使用public保護,而不是爲好。更多阿布德訪問speicifiers here

public class Base 
{ 
    public Panel panel {get; set;}; 
    public Base(Panel panel1) 
    { 
     panel = panel1; 
    } 
} 


public class Derived : Base 
{ 
    public Derived() : base(new Panel()) 
    { 
      // this.panel 
    } 
} 
0

兩種方式:

public class Derived : Base 
{ 
    Panel aPanel; 

    public Derived() : this(new Panel()) {} 

    public Derived(Panel panel) : base(aPanel) 
    { 
     //Use aPanel Here. 
    } 
} 

OR

public class Base 
{ 
    protected Panel aPanel; 

    public Base(Panel panel1) 
    { 
     aPanel = panel1 
    } 
} 
+0

第一個不起作用。 – ispiro

0
public class Base 
{ 
    // Protected to ensure that only the derived class can access the _panel attribute 
    protected Panel _panel; 
    public Base(Panel panel1) 
    { 
     _panel = panel1; 
    } 
} 

public class Derived : Base 
{ 
    public Derived() : base(new Panel()) 
    { 
     // refer this way: base.panel 
    } 
} 


另外,如果你想只提供一個獲取,而不是一組派生類可以這樣做:

public class Base 
    { 
     // Protected to ensure that only the derived class can access the _panel attribute 
     private Panel _panel; 
     public Base(Panel panel1) 
     { 
      _panel = panel1; 
     } 

     protected Panel Panel 
     { get { return _panel; } } 
    } 

    public class Derived : Base 
    { 
     public Derived() : base(new Panel()) 
     { 
      // refer this way: base.Panel (can only get) 
     } 
    }