Subscribing to events
When subscribing to events in .NET do I need to create a new instance of the delegate such as
toolbarControl1.OnUploadEventHandler +=
new ToolbarControl.UploadEventHandler(toolbarControl1_OnUpload);
Or is it better to do the following?
开发者_如何学编程toolbarControl1.OnUploadEventHandler += toolbarControl1_OnUpload;
Thanks in advance.
The second one takes less coding and both mean the same.
You might want to consider using generic version of EventHandler - EventHandler<TEventArgs>
. You will save on declaring all those delegates.
You can also use lambda expressions, ie.
toolbarControl1.OnUploadEventHandler +=
(sender, args) => { /* Your code goes here */ };
You can do both, so its your preference.
You can also do things like this for very simple handlers to save writing a delegate function:
toolbarControl1.OnUploadEventHandler += (s, e) => uploadCount +=1;
The code speaks for itself:
using System;
class Program
{
void SomeMethod(object sender, EventArgs e) { }
event EventHandler SomeEvent;
static void Main(string[] args)
{
var prog = new Program();
// Demonstrate that they are equivalent
prog.SomeEvent += new EventHandler(prog.SomeMethod);
prog.SomeEvent -= prog.SomeMethod; // Sugar for new EventHandler(prog.SomeMethod)
Console.WriteLine("Number of SomeEvent subscribers is {0}", (prog.SomeEvent != null ? prog.SomeEvent.GetInvocationList() : new Delegate[0]).Length);
// Why are they equivalent?
var d1 = new EventHandler(prog.SomeMethod);
var d2 = new EventHandler(prog.SomeMethod);
Console.WriteLine("Delegates are reference equal {0}", Object.ReferenceEquals(d1, d2));
Console.WriteLine("Delegates are equivalent {0}", d1 == d2);
}
}
They are equivalent. The second one only provides better readability.
They are equivalent unless you need to keep a reference to the delegate so as to unsubscribe.
精彩评论