这是一个与我之前看到的答案略有不同的问题,或者我没有得到它。我有一个父类,它有一个名为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()
函数。
我该怎么做呢?
发布于 2012-12-07 00:42:26
找到了解决方案。
在父类中,我声明了ChildClass()的一个新实例,然后将该类中的事件处理程序绑定到父类中的本地方法
在子类中,我添加了一个公共事件处理程序:
public EventHandler UpdateProgress;
在父类中,我创建了这个子类的一个新实例,然后将本地父事件绑定到子类中的public
eventhandler
ChildClass child = new ChildClass();
child.UpdateProgress += this.MyMethod;
child.LoadData(this.MyDataTable);
然后在子类的LoadData()
中,我可以调用
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());
}
}
这将在父类中运行事件
发布于 2012-12-06 20:28:21
若要访问父类的属性和方法,请使用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
,子类才能访问它。
发布于 2015-08-27 00:40:28
跟进suhendri对Rory的评论。下面是一个Action委托示例:
在子添加中:
public Action UpdateProgress; // In place of event handler declaration
// declare an Action delegate
.
.
.
private LoadData() {
this.UpdateProgress(); // call to Action delegate - MyMethod in
// parent
}
在父添加中:
// The 3 lines in the parent becomes:
ChildClass child = new ChildClass();
child.UpdateProgress = this.MyMethod; // assigns MyMethod to child delegate
https://stackoverflow.com/questions/13743609
复制相似问题