【发布时间】:2018-05-04 06:57:27
【问题描述】:
基类
class TestBase
{
protected int a;
protected int b;
public TestBase(int i)
{
a = i;
}
protected TestBase()
{
}
public void Update(int i)
{
a = i;
TestChild child = new TestChild();
child.Update("Hello World ");
}
儿童班
class TestChild:TestBase
{
private string msg;
public void Update (string s)
{
msg = s+ a.ToString();
Console.WriteLine("msg=" + msg);
}
}
通话
private void btnTest_Click(object sender, EventArgs e)
{
TestBase t = new TestBase(1);
t.Update(100);
}
结果 你好世界 0
问题 我希望得到 Hello World 100。显然子类没有访问基类变量 int a。我该怎么做?
【问题讨论】:
-
为什么要在
TestBase.Update中创建TestChild实例?这没有意义。 -
你应该在你的主类中创建
TestChild而不是在你的基类中 -
为什么投反对票?他清楚地陈述了他的问题:到目前为止他做了什么,错误的结果是什么以及他的期望是什么。如果您不喜欢他的编码方式,那么您的答案就有一个很好的主题。停止从人们那里窃取积分。
标签: c# inheritance