Difference between wiring events with and without "new"
In C#, what is the difference (if any) between these two lines of code?
tmrMain.Elapsed += new ElapsedEventHandler(tmrMain_Tick);
and
tmrMain.Elapsed += tmrMain_Tick;
Both appear to work exactly the same. Does C# just assume you mean the former when you type the latter?
I did this
static void Hook1()
{
someEvent += new EventHandler( Program_someEvent );
}
static void Hook2()
{
someEvent += Program_someEvent;
}
And then ran ildasm over the code.
The generated MSIL was exactly the same.
So to answer your question, yes they are the same thing.
The compiler is just inferring that you want someEvent += new EventHandler( Program_someEvent );
-- You can see it creating the new EventHandler
object in both cases in the MSIL
It used to be (.NET 1.x days) that the long form was the only way to do it. In both cases you are newing up a delegate to point to the Program_someEvent method.
I don't think there's any difference. Certainly resharper says the first line has redundant code.
链接地址: http://www.djcxy.com/p/51492.html上一篇: 我应该在匿名JavaScript函数中封装功能块吗?
下一篇: 有和没有“新”的接线事件之间的区别