从子类c#调用父方法

CR4*_*G14 27 .net c#

这是一个与我之前看到的答案略有不同的问题,或者我没有得到它.我有一个父类,有一个名为的方法MyMethod()和一个变量public Int32 CurrentRow;

public void MyMethod()
{    
     this.UpdateProgressBar();    
}
Run Code Online (Sandbox Code Playgroud)

在父级中我创建了一个新的实例 ChildClass

Boolean loadData = true;
if (loadData) 
{    
     ChildClass childClass = new ChildClass();    
     childClass.LoadData(this.Datatable);    
}
Run Code Online (Sandbox Code Playgroud)

在子类LoadData()方法中,我希望能够设置CurrentRow父类的变量并调用该MyMethod()函数.

我该怎么做呢?

Ror*_*san 56

要访问父类的属性和方法,请使用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...
    }
}
Run Code Online (Sandbox Code Playgroud)

请注意,您还必须更改父级的访问修饰符,MyMethod()以便至少protected让子类访问它.

  • 这正是我所寻找的,即使这不是他的问题:).问题标题令人困惑...... (3认同)

CR4*_*G14 10

找到了解决方案.

在父类中,我声明了一个ChildClass()的新实例,然后将该类中的事件处理程序绑定到父类中的本地方法

在子类中,我添加了一个公共事件处理程序:

public EventHandler UpdateProgress;
Run Code Online (Sandbox Code Playgroud)

在父级中,我创建此子类的新实例,然后将本地父事件绑定到子级public eventhandler

ChildClass child = new ChildClass();
child.UpdateProgress += this.MyMethod;
child.LoadData(this.MyDataTable);
Run Code Online (Sandbox Code Playgroud)

然后在LoadData()我可以打电话的儿童班

private LoadData() {
    this.OnMyMethod();
}
Run Code Online (Sandbox Code Playgroud)

在哪里OnMyMethod:

public void OnMyMethod()
{
     // has the event handler been assigned?
     if (this.UpdateProgress!= null)
     {
         // raise the event
         this.UpdateProgress(this, new EventArgs());
     }
}
Run Code Online (Sandbox Code Playgroud)

这将在父类中运行该事件

  • 根据您的意图,使用 Action delegate 可能比 EventHandler 更好。出于一个原因,您不必担心删除事件分配,即:child.UpdateProgress -= this.MyMethod; (2认同)

小智 5

跟进 suhendri 对 Rory McCrossan 回答的评论。这是一个 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
}
Run Code Online (Sandbox Code Playgroud)

在父级中添加:

// The 3 lines in the parent becomes:
ChildClass child = new ChildClass();
child.UpdateProgress = this.MyMethod;  // assigns MyMethod to child delegate
Run Code Online (Sandbox Code Playgroud)