Why do event handlers always have a return type of void?

前端 未结 11 2135
夕颜
夕颜 2020-12-05 23:30

Hey, I wondered why is it that the return type of events such as

private void button1_Click(object sender, EventArgs e)

is always void?

11条回答
  •  借酒劲吻你
    2020-12-06 00:03

    the default EventHandler delegate defined this signature. However, you are free to create your own events with your own return types if you wish.

    public class AnEvent
    {
      public delegate MyReturnType MyDelegateName();
      public event MyDelegateName MyEvent;
    
      public void DoStuff()
      {
        MyReturnType result = null;
        if (MyEvent != null)
          result = MyEvent();
        Console.WriteLine("the event was fired");
        if (result != null)
          Console.Writeline("the result is" + result.ToString());
      }
    }
    
    public class EventListener
    {
      public EventListener()
      {
        var anEvent = new AnEvent();
        anEvent.MyEvent += SomeMethod;
      }
    
      public MyReturnType SomeMethod()
      {
        Console.Writeline("the event was handled!");
        return new MyReturnType;
      }
    }
    

提交回复
热议问题