Why events can't be used in the same way in derived classes as in the base class in C#?

前端 未结 6 1316
庸人自扰
庸人自扰 2020-11-29 07:27

In following code, I want to extend the behaviour of a class by deriving/subclassing it, and make use of an event of the base class:

public class A
{
    pub         


        
6条回答
  •  心在旅途
    2020-11-29 07:51

    My answer would be that you shouldn't have to do this.

    C# nicely enforces Only the type declaring/publishing the event should fire/raise it. If the base class trusted derivations to have the capability to raise its events, the creator would expose protected methods to do that. If they don't exist, its a good hint that you probably shouldn't do this.

    My contrived example as to how different the world would be if derived types were allowed to raise events in their ancestors. Note: this is not valid C# code.. (yet..)

    public class GoodVigilante
    {
      public event EventHandler LaunchMissiles;
    
      public void Evaluate()
      {
        Action a = DetermineCourseOfAction(); // method that evaluates every possible
    // non-violent solution before resorting to 'Unleashing the fury'
    
        if (null != a) 
        { a.Do(); }
        else
        {  if (null != LaunchMissiles) LaunchMissiles(this, EventArgs.Empty); }
      }
    
      virtual protected string WhatsTheTime()
      {  return DateTime.Now.ToString();  }
      ....   
    }
    public class TriggerHappy : GoodVigilante
    {
      protected override string WhatsTheTime()
      {
        if (null != LaunchMissiles) LaunchMissiles(this, EventArgs.Empty);
      }
    
    }
    
    // client code
    GoodVigilante a = new GoodVigilante();
    a.LaunchMissiles += new EventHandler(FireAway);
    GoodVigilante b = new TriggerHappy();             // rogue/imposter
    b.LaunchMissiles += new EventHandler(FireAway);
    
    private void FireAway(object sender, EventArgs e)
    {
      // nuke 'em
    }
    

提交回复
热议问题