我在孩子班级继承了财产。但是,当我尝试调用父方法时,它总是使用它自己的(父)属性。如何解释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.
抱歉,这绝对是愚蠢的问题。但是我还是需要您的帮助。
autoinc
子类中的field会隐藏父类中具有相同名称的字段声明。只需从子类中删除该字段即可:
class ChildClass : ParentClass
{
public ChildClass()
{
autoinc = 2000;
}
}
记住,当您使用继承时,Child对象就是Parent对象。您无需在子对象中定义父字段或其他成员,因为它们都已经在这里。除非您想隐藏或覆盖父类的某些成员。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句