从子类C#调用父方法 [英] Call parent method from child class c#
问题描述
这是一个与我以前看到的答案或我没有得到的答案稍有不同的问题.我有一个父类,它的方法名为 MyMethod()
和变量 public Int32 CurrentRow;
This is a slightly different question from previous answers I have seen or I am not getting it. I have a parent class with a method named MyMethod()
and a variable public Int32 CurrentRow;
public void MyMethod()
{
this.UpdateProgressBar();
}
在父级中,我创建一个 ChildClass
In the parent I create a new instance of ChildClass
Boolean loadData = true;
if (loadData)
{
ChildClass childClass = new ChildClass();
childClass.LoadData(this.Datatable);
}
在子类 LoadData()
方法中,我希望能够设置父类的 CurrentRow
变量并调用 MyMethod()
功能.
In the child Class LoadData()
method I want to be able to set the CurrentRow
variable of the parent and call the MyMethod()
function.
我该怎么做?
推荐答案
找到了解决方案.
在父级中,我声明ChildClass()的新实例,然后将该类中的事件处理程序绑定到父级中的本地方法
In the parent I declare a new instance of the ChildClass() then bind the event handler in that class to the local method in the parent
在子类中,我添加一个公共事件处理程序:
In the child class I add a public event handler:
public EventHandler UpdateProgress;
在父级中,我创建此子级类的新实例,然后将本地父级事件绑定到子级中的 public
eventhandler
In the parent I create a new instance of this child class then bind the local parent event to the public
eventhandler
in the child
ChildClass child = new ChildClass();
child.UpdateProgress += this.MyMethod;
child.LoadData(this.MyDataTable);
然后在我可以调用的子类的 LoadData()
中
Then in the LoadData()
of the child class I can call
private LoadData() {
this.OnMyMethod();
}
OnMyMethod
所在的位置:
public void OnMyMethod()
{
// has the event handler been assigned?
if (this.UpdateProgress!= null)
{
// raise the event
this.UpdateProgress(this, new EventArgs());
}
}
这将在父类中运行事件
这篇关于从子类C#调用父方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!