问题
Possible Duplicate:
Should I Create a New Delegate Instance?
Hi, I've tried searching for the answer to this, but don't really know what terms to search for, and none of the site-suggested questions are relevant. I'm sure this must have been answered before though.
Basically, can somebody tell me what's the difference between these two lines in C#:
SomeEvent += SomeMethod
SomeEvent += new SomeDelegate(SomeMethod)
For example:
DataContextChanged += App_DataContextChanged;
DataContextChanged += new DependencyPropertyChangedEventHandler(App_DataContextChanged);
They both seem to do the same thing.
回答1:
They are the same. The second variant is just a shorthand for the first called Method group conversion
.
Simply put, the compiler infers what the type of the delegate is by using the delegate type of the event itself. This was introduced in C#2.0 if I'm not mistaken.
回答2:
they do the same thing. The variation
SomeEvent += new SomeDelegate(SomeMethod)
was the only way to write it in C# 1.0, 1.1 . Since 2.0 you can write the other alternative as a simplification.
回答3:
Both are same.
SomeEvent += new SomeDelegate(SomeMethod)
mentions what happens under the hood i.e SomeDelegate constructor is called to create a instance of the object.
来源:https://stackoverflow.com/questions/4679369/c-whats-the-difference-between-someevent-method-and-someevent-new-deleg