我从无参数构造函数类派生一个类,如下所示:
public class Base
{
public Base(Panel panel1)
{
}
}
public class Derived : Base
{
public Derived() : base(new Panel())
{
//How do I use panel1 here?
}
}
如何在Derived中引用panel1?
(欢迎简单的解决方法。)
答案 0 :(得分:4)
Adil的回答假定您可以修改Base
。如果你不能,你可以这样做:
public class Derived : Base
{
private Panel _panel;
public Derived() : this(new Panel()) {}
private Derived(Panel panel1) : base(panel1)
{
_panel = panel1;
}
}
答案 1 :(得分:1)
您需要在Panel
中定义Base
,您也可以使用受保护的代替public
。阅读更多aboud access 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
}
}
答案 2 :(得分: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
}
}
答案 3 :(得分: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
}
}
此外,如果您只想为派生类提供get而不是set,则可以执行以下操作:
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)
}
}