编写内联事件处理程序是一种不好的做法吗

发布于 2024-09-29 19:25:40 字数 1695 浏览 6 评论 0原文

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

小猫一只 2024-10-06 19:25:40

这绝对没问题 - 尽管有两个警告:

  • 如果您要在闭包内修改局部变量,您应该确保您了解自己在做什么。
  • 您将无法取消订阅该事件

通常我只内联非常简单的事件处理程序 - 对于更多涉及的内容,我使用 lambda 表达式(或匿名方法)通过调用以下方法来订阅更合适的方法:

// We don't care about the arguments here; SaveDocument shouldn't need parameters
saveButton.Click += delegate { SaveDocument(); };

It's absolutely fine - although there are two caveats:

  • If you're modifying a local variable from within a closure, you should make sure you understand what you're doing.
  • You won't be able to unsubscribe from the event

Typically I only inline really simple event handlers - for anything more involved, I use lambda expressions (or anonymous methods) to subscribe with a call to a method with a more appropriate method:

// We don't care about the arguments here; SaveDocument shouldn't need parameters
saveButton.Click += delegate { SaveDocument(); };
影子的影子 2024-10-06 19:25:40

在大多数情况下,我宁愿使用像“timer_Tick()”这样的单独方法,但我更愿意将其称为 OnTimerTick() ,如下所示:

  • 当我阅读该类时,更清楚小麦正在发生。 “On”告诉我它可以事件处理程序。
  • 在“内联”情况下,在方法中设置断点更容易。
  • 该事件在“Foo”承包商返回后很长时间内被触发,并且我不认为它在承包商的范围内运行。

但是,如果事件仅在内联声明的方法返回之前触发,并且设置事件的对象的范围仅限于声明方法,那么我认为“内联”版本更好。因此,我喜欢使用“in line”将比较委托传递给“sort”方法。

In most cases I would rather have the separate methods like “timer_Tick()”, however I should rather it be called OnTimerTick() as:

  • When I read the class, it is clearer wheat is going on. The “On” tells me its can event handler.
  • It is easier to set a break point in the method in the “inline” case.
  • The event is fired a long time after “Foo” contractor has returned, and I don’t think it as running in t the scope of the contractor.

However if the event will only be fired before the method it is declared in-line returns and the object the event is set on has a scope what that is limited to the declaring method, then I think the “in line” version is better. Hence I like using “in line” for the compare delegate being passed to a “sort” method.

剪不断理还乱 2024-10-06 19:25:40

您将两个样本放在一起。显然,第二个选项(您不喜欢它)是最具可读性的。

代码的可读性和可维护性非常重要。保持事情简单,尽可能容易理解。大多数人通常认为 Lambda 表达式更难理解。即使它们对你来说是第二天性,对其他人来说可能不是。

You put the two samples together. It is clear that the second option (which you don't prefer) is the most readable.

Code readability and maintainability are very important. Keep things simple, as easy as possible to understand. Lambda expressions are generally considered harder to understand by majority of people. Even if they are a second nature for you for others might not.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文