0
class A
{
  public event EventHanler MyEvent;
  protected virtual void OnMyEvent(EventArgs e)
  {
    if (MyEvent!=null) 
        MyEvent(this, e);
  }

   public void DoEvent()
   {
    //................
      MyEvent(this, new EventArgs());
   }
}




class B: A
{
  private A a = new A();
  public B ()
  {
    a.MyEvent += MyMethod;
  }
  public void MyMethod(object sender, EventArgs e)
  {
       Console.WriteLine("Event handler");
  }
}



class C : A
{
  private A a = new A();

   protected override void OnMyEvent(EventArgs e)
   {
     base.OnMyEvent(e); 
     Console.WriteLine("OnMyEvent overriding");
  }
}

我订阅了该事件并覆盖了类中的方法 OnMyEvent()BC. 注意调用方法base.OnMyEvent(e)是在方法的开头C.OnMyEvent(...)

就我而言,这里没有区别。换句话说,如果我base.OnMyEvent(e)在覆盖方法的开头调用,这意味着我只是订阅事件吗?

实际上没有区别吗?

4

1 回答 1

1

它们是有区别的:

  • 调用C.OnMyEvent() 加注 MyEvent。(相反, raiseMyEvent不会调用C.OnMyEvent()。)
  • B.MyMethod 把柄 MyEvent。因此, raiseMyEvent将调用B.MyMethod. (相反,调用B.MyMethod不会引发MyEvent。)
于 2012-04-25T20:37:58.213 回答