何时/为什么使用EventHandler而不仅仅是常规事件?

时间:2016-08-24 22:26:07

标签: c# events event-handling eventhandler

使用EventHandler并仅定义事件的功能是否存在差异?

1 个答案:

答案 0 :(得分:2)

这是两件不同的事情

event宣布一个事件:

https://msdn.microsoft.com/en-us/library/8627sbea.aspx

EventHandler定义事件将引发的方法:

https://msdn.microsoft.com/en-us/library/system.eventhandler(v=vs.110).aspx

EventHandler<TEventArgs>是您自定义EventArgs的便捷包装:

https://msdn.microsoft.com/en-us/library/db0etb8x(v=vs.110).aspx

订阅活动的不同方式

using System;

namespace ConsoleApplication3
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            // using a method
            MyEvent += Program_MyEvent;

            // using EventHandler, possible but not mandatory
            MyEvent += new EventHandler(Target);

            // using lambda syntax
            MyEvent += (sender, eventArgs) => { };

            // using delegate
            MyEvent += delegate (object sender, EventArgs eventArgs) { };

            // using delegate, signature is optional actually
            MyEvent += delegate { };
        }

        private static void Target(object sender, EventArgs eventArgs)
        {
        }

        private static void Program_MyEvent(object sender, EventArgs e)
        {
        }

        public static event EventHandler MyEvent;
    }

}