C#:显式调用事件处理程序真的是“一件好事"吗?

C#: is calling an event handler explicitly really quot;a good thing to doquot;?(C#:显式调用事件处理程序真的是“一件好事吗?)
本文介绍了C#:显式调用事件处理程序真的是“一件好事"吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题与 C# 有关,但也可能适用于其他语言.我对使用如下代码持保留态度:

This question is related to C#, but may be applicable to other languages as well. I have a reservation against using code such as the following:

using System.Windows.Forms;

class MyForm : Form
{
    private Timer myTimer;
    private Button myButton;

    public MyForm()
    {
        // Initialize the components, etc.

        myTimer.Tick += new EventHandler( myTimer_Tick );
        myButton.Click += new EventHandler( myButton_Click );

        myTimer.Start();
    }

    private void myTimer_Tick( object sender, EventArgs eventArgs )
    {
        myTimer.Stop();
        // also, I see a lot of usage of 
        // Timer.Enabled = true/false instead of -^
        myButton_Click( this, ea /* or event EventArgs.Empty, or null */ );
        return;
    }

    private void myButton_Click( object sender, EventArgs eventArgs )
    {
        // do a lot of stuff, with lots of logic that doesn't even use the
        // state of the eventArgs
        return;
    }
}

只有我一个人吗,上面的风格是我最讨厌的?是否还有其他人喜欢将事件处理与函数的工作负载分离,甚至将复杂的例程分离到单独的函数中?

Am I alone, in that the above style is a pet peeve of mine? Are there others who enjoy the clarity of separating event handling from the workload of functions, or even separating out complex routines into separate functions?

甚至有公认的风格吗?我觉得 C# 中的事件处理所具有的任何表现力和灵活性都可能会因为这样的样式而丢失.我觉得如果您有一个表示已单击按钮"的方法,则仅应在单击按钮时调用它.

Is there even an accepted style? I feel like any expressiveness and flexibility that event handling in C# has can be lost with styles like this. I feel like if you have a method that means "a button has been clicked", then it should only be called when a button is clicked.

对于这样写的人,我想说:如果您坚持使用 EventHandler 方法来处理您的计时器滴答声和按钮单击,则将其命名为 button_Click 以外的其他名称——也许是handleUserEvent(object发件人,EventArgs eventArgs )".

To those who write like this, I would say: if you insist on having an EventHandler method to handle your timer tick, and your button click, then call it something other than button_Click -- perhaps "handleUserEvent( object sender, EventArgs eventArgs )".

实际上,问题是,是否有任何广泛使用的样式指南支持或阻止上述使用?

Really, though, the question is, are there any style guidelines that are widely used which either support or discourage usage such as the above?

推荐答案

我同意 Rex M 的回答,但我会更进一步.如果您使用的是 MVC 模式(或类似模式),则视图会将按钮单击委托给控制器.控制器方法当然可以从您的类中的其他地方调用 - 例如,从您的计时器回调中.

I agree with Rex M's answer, but I'd take it one step further. If you are using the MVC pattern (or something similar), the view would delegate the button click to the controller. The controllers methods can of course be called from elsewhere in your class - say, from your timer callback.

那么,回到你原来的代码:

So, back to your original code:

using System.Windows.Forms;

class MyForm : Form
{
    private Timer myTimer;
    private Button myButton;

    private MyController myController;

    public MyForm()
    {
        // ...
        // Initialize the components, etc.
        // ...

        myTimer.Tick += new EventHandler( myTimer_Tick );
        myButton.Click += new EventHandler( myButton_Click );

        myTimer.Start();
    }

    private void myTimer_Tick( object sender, EventArgs eventArgs )
    {
        myTimer.Stop();
        myController.SomeMethod()
    }

    private void myButton_Click( object sender, EventArgs eventArgs )
    {
        // All the stuff done here will likely be moved 
        // into MyController.SomeMethod()
        myController.SomeMethod();
    }
}

使用 MVC 的一个优点是控制器与视图的分离.控制器现在可以轻松地跨多种视图类型使用,并且退出的 GUI 更易于维护,因为它们包含的应用程序逻辑非常少.

One advantage of using MVC is the decoupling of the controller from the view. The controller can now be used across multiple view types easily and exiting GUIs are easier to maintain as they contain very little application logic.

添加以响应 OP 的评论

Added in response to comments from the OP

软件工程的基本设计原则谈到耦合和内聚.重要的是,我们努力在最大限度地减少组件之间的耦合的同时最大限度地提高内聚力,因为这会产生一个更加模块化和可维护的系统.MVC 等模式和 Open/Closed Principal 等原则建立在这些基础之上,为开发人员提供了更具体的实施模式.

The fundamental design principals of software engineering talk about coupling and cohesion. Importantly we strive to minimise coupling between components while maximising cohesion as this leads to a more modular and maintainable system. Patterns like MVC and principals like the Open/Closed Principal build on these fundamentals, providing more tangible patterns of implemenation for the developer to follow.

因此,任何编写原始帖子中的代码的人都没有理解软件设计的基础知识,需要大量发展他们的技能.应该赞扬 OP 识别这种代码气味"并试图理解为什么它不太正确.

So, anyone who writes code as seen in the original post has not understood the fundamentals of software design and needs to develop their skills considerably. The OP should be commended for identifying this "code smell" and trying to understand why it's not quite right.

一些相关参考资料:

  • http://en.wikipedia.org/wiki/Coupling_(computer_science)
  • http://en.wikipedia.org/wiki/Cohesion_(computer_science)
  • http://en.wikipedia.org/wiki/Loose_coupling
  • http://en.wikipedia.org/wiki/Model–view–controller
  • http://en.wikipedia.org/wiki/Design_patterns
  • http://en.wikipedia.org/wiki/Open/closed_principle
  • http://en.wikipedia.org/wiki/Design_Patterns_(book)
  • http://en.wikipedia.org/wiki/Coupling_(computer_science)
  • http://en.wikipedia.org/wiki/Cohesion_(computer_science)
  • http://en.wikipedia.org/wiki/Loose_coupling
  • http://en.wikipedia.org/wiki/Model–view–controller
  • http://en.wikipedia.org/wiki/Design_patterns
  • http://en.wikipedia.org/wiki/Open/closed_principle
  • http://en.wikipedia.org/wiki/Design_Patterns_(book)

这篇关于C#:显式调用事件处理程序真的是“一件好事"吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)