在C#中,如何从子类访问基类变量值

ppau2004

基类

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 World100。显然,子类未访问基类变量int a。我怎样才能做到这一点?

科维罗利

如果您想获得预期的结果,请statica和/或b变量放置一个修饰符,如下所示:

  static protected int a;
  static protected int b;

之后,如果按下该按钮,它将写出:

msg=Hello World 100

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章