【问题标题】:How to explain to C# to use inherited property instead of parent?如何向 C# 解释使用继承属性而不是父属性?
【发布时间】:2017-01-23 11:19:02
【问题描述】:

我在我的子类中继承了财产。但是当我试图调用父方法时,它总是使用它自己的(父)属性。我如何解释 c# 使用继承的属性?

class ParentClass 
{
    protected int autoinc;

    public ParentClass()
    {
        autoinc = 1000;
    }

    public Show()
    {
        Debug.Log("AutoInc = " + autoinc);
    }

}

class ChildClass : ParentClass
{
    protected int autoinc;

    public ChildClass()
    {
        autoinc = 2000;
    }
}

/* Calling code */
ChildClass cc = new ChildClass();
cc.Show();

// I need above code to show 2000, but it shown 1000.

对不起,这绝对是个愚蠢的问题。但无论如何我都需要你的帮助。

【问题讨论】:

  • 这些都不是属性——它们是字段。它们非常不同,了解这种差异至关重要。字段不能是虚拟的 - ParentClass.Show始终使用在 ParentClass 中声明的字段。但是为什么要声明两个不同值的字段,而不是在ChildClass构造函数中将autoinc的值设置为2000呢?
  • VS 应该显示一个警告,提示您应该使用 new 关键字。无论您想做什么,我都建议您以不同的方式进行。
  • @JonSkeet 是的,看,我已更改代码以在 2000 年之前在子类中初始化 autoinc。但无论如何它显示 1000。
  • @Epsiloncool:不,您的代码仍在 ChildClass 中声明 separate 字段。删除该声明:您只需要一个字段。

标签: c# class variables inheritance


【解决方案1】:

autoinc 子类中的字段隐藏了父类中同名字段的声明。只需从子类中删除该字段:

class ChildClass : ParentClass
{
    public ChildClass()
    {
        autoinc = 2000;
    }
}

记住,当你使用继承时,子对象就是父对象。您不需要在子对象中定义父字段或其他成员,因为它们都已经在这里了。除非您想隐藏覆盖父类的某些成员。

【讨论】:

    猜你喜欢
    • 2013-11-16
    • 2014-02-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多