【问题标题】:Difference between event Action and event EventHandler<EventArgs> [duplicate]事件 Action 和事件 EventHandler<EventArgs> 之间的区别 [重复]
【发布时间】:2015-07-07 16:07:17
【问题描述】:

用Action声明事件时有什么问题

public interface ISomething
{
    event Action MyEventName;
}

public interface ISomething
{
    event Action<bool> MyBoolEventName;
}

而不是前面代码的其他变体使用 EventHandler 和 EventArgs 声明事件

public interface ISomething
{
     event EventHandler<EventArgs> MyEventName;
}

public class EventArgsWithBool : EventArgs
{
    private readonly bool someValue;

    public EventArgsWithBool (bool someValue)
    {
        this.someValue = someValue;
    }

    public bool SomeValue
    {
        get { return this.someValue; }
    }
}

public interface ISomething
{
     event EventHandler<EventArgsWithBool> MyBoolEventName;
}

我的想法:

两个版本对我来说都很好,我认为第一个版本更易读/看起来更直接。但一些开发人员表示,最好在 EventArgs 中使用第二种语法,但无法给出很好的技术理由(除了他们知道第二种语法)。

使用第一个有什么技术问题吗?

【问题讨论】:

标签: c# coding-style eventhandler eventargs


【解决方案1】:

当您使用 Action 时,您不会将 Sender 对象传递给事件处理程序。有时,事件处理程序知道是什么对象触发了事件很有用。

【讨论】:

  • 我也可以使用 Action 并明确设置它,但在这种情况下你是对的。
猜你喜欢
  • 2010-11-28
  • 1970-01-01
  • 1970-01-01
  • 2012-03-04
  • 2013-05-20
  • 2023-01-26
  • 1970-01-01
  • 2011-11-18
相关资源
最近更新 更多