既然我们有多播委托,为什么我们需要事件?

Since we have multicast delegates, why do we need events?

我在一次采访中被问到这个问题,我要么是脑筋急转弯,要么就是很笨,但我没有回答。

我们需要活动的几个原因:

  • 限制范围,你不想公开你的事件,就像你可以为你的代表一样。
  • 您可以将事件作为接口中的字段而不是委托

示例如下:

Class Printer
{
    public event EventHandler Print;

    public void Start()
    {
        OnPrint();
    }

    protected virtual void OnPrint()
    {
        Print?.Invoke(this,EventArgs.Empty);
    }
}
class Program
{
    static void Main(string[] args)
    {
        //When Print is an EventHander
        var printer = new Printer();
        printer.Print += PrintEvent;
        printer.Start();

        //If Print was a delegate this is possible, else you get compile time errors 
        printer.Print(null,null); // Events will not allow to have a direct invoke 
        printer.Print = null; //You cannot assign a null to an Event Handler
    }
    private static void PrintEvent(object sender, EventArgs e)
    {
        System.Console.WriteLine("Printing event");
    }
}