删除多余的委托构造函数调用?
我下载了 ReSharper,它告诉我更改这一行:
dispMap.OnDraw += new EventHandler(dispMap_OnDraw);
更改为这一行:
dispMap.OnDraw += dispMap_OnDraw;
因为第一行是“冗余委托构造函数调用”。
这是真的吗?在自动生成的表单设计器代码中,语法基于第一段代码,当输入 dispMap.OnDraw +=
并按 TAB 键时,IDE 会自动生成 new EventHandler(dispMap_OnDraw)< /code>
我只是对这个感到好奇。 ReSharper 有道理吗?
I downloaded ReSharper and it is telling me to change this line:
dispMap.OnDraw += new EventHandler(dispMap_OnDraw);
To be this line:
dispMap.OnDraw += dispMap_OnDraw;
Because the first line is a "redundant delegate constructor call."
Is this true? In the automatically generated designer code for forms the syntax is based on the first piece of code and when typing in dispMap.OnDraw +=
and hitting TAB the IDE automatically generates new EventHandler(dispMap_OnDraw)
I'm just curious about this one. Does ReSharper have a point?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
是的,这是正确的。我在几个案例中都这样做过。
委托构造函数调用应该是隐式的;该类型可以从
OnDraw
推断出来,并根据dispMap_OnDraw
的方法签名进行验证。此外,这篇 MSDN 文章 中的引用似乎是相关的:
我相信无论哪种方式都会创建委托实例,但由于在隐式实例化时没有委托的对象引用,因此无法使用
-=
运算符将其删除。Yes, this is correct. I have done this in several cases.
The delegate constructor call should be implicit; the type can be inferred from
OnDraw
and validated against the method signature ofdispMap_OnDraw
.Also, a quote from this MSDN article appears relevant:
I believe the delegate instance is created either way, but since you don't have an object reference for the delegate when you implicitly instantiate, you can't remove it with the
-=
operator.这确实有道理。第二行是第一行的简写。根据您的编码标准/约定,您可以使用其中任何一个,但第一个确实会增加很多噪音。
It does have a point. The second line is shorthand for the first. Depending on your coding standards/conventions, you could use either one, but the first one does add a lot of noise.
如果您比较这两种情况下生成的 IL,您会发现它们是相同的。以下是 C# 中的两种情况以及它们产生的 IL。
示例 C#:
这是构造函数的 IL。请注意
IL_000a
至IL_0028
行。结论:我认为没有任何理由更改您的代码,它们是等效的。
If you compare the IL generated in both cases, you'll see that they are the same. Here's both cases in C#, and the IL they result in.
Example C#:
Here's the IL for the constructor. Pay attention to lines
IL_000a
throughIL_0028
.Conclusion: I don't see any reason to change your code, they are equivalent.
它工作得很好,我有 DevExpress,它也告诉我同样的事情!
it works fine, I have DevExpress and it tells me the same!