什么时候/为什么要使用eventandler而不是普通的Event



使用eventandler和仅仅定义Event在功能上有区别吗?

这是两回事

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;
    }
}

相关内容

  • 没有找到相关文章

最新更新