使用eventandler和仅仅定义Event在功能上有区别吗?
这是两回事
event
声明一个事件:
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;
}
}