这个问题与我之前看到的答案略有不同,或者我不明白。我有一个父类,其中包含一个名为 MyMethod()
的方法和一个变量 public Int32 CurrentRow;
public void MyMethod()
{
this.UpdateProgressBar();
}
在父类中,我创建了一个新的 ChildClass
实例
Boolean loadData = true;
if (loadData)
{
ChildClass childClass = new ChildClass();
childClass.LoadData(this.Datatable);
}
在子类 LoadData()
方法中,我希望能够设置父类的 CurrentRow
变量并调用 MyMethod()
功能。
我该怎么做?
最佳答案
要访问父类的属性和方法,请使用 base
关键字。所以在你的子类 LoadData()
方法中你会这样做:
public class Child : Parent
{
public void LoadData()
{
base.MyMethod(); // call method of parent class
base.CurrentRow = 1; // set property of parent class
// other stuff...
}
}
请注意,您还必须将父类 MyMethod()
的访问修饰符更改为至少 protected
以便子类访问它。
关于c# - 从子类调用父方法c#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13743609/