这是一个与我之前看到的答案略有不同的问题,或者我没有得到它.我有一个父类,有一个名为的方法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()函数.
我该怎么做呢?
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...
    }
}
请注意,您还必须更改父级的访问修饰符,MyMethod()以便至少protected让子类访问它.
CR4*_*G14 10
找到了解决方案.
在父类中,我声明了一个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());
     }
}
这将在父类中运行该事件
小智 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
}
在父级中添加:
// The 3 lines in the parent becomes:
ChildClass child = new ChildClass();
child.UpdateProgress = this.MyMethod;  // assigns MyMethod to child delegate