简体   繁体   English

自定义事件处理程序

[英]Custom EventHandler

Is it a good practice to pass in a custom non EventArgs class to an EventHandler as such:将自定义的非 EventArgs class 传递给 EventHandler 是否是一种好习惯:

public event EventHandler<FooBar> FooBarCreated;

instead of代替

public event EventHandler<FooBarCreatedEventArgs> FooBarCreated;

public class FooBarCreatedEventArgs : EventArgs 
{
    ...

    public FooBar FooBar { get; }
}

The former is shorter but I seem to see the latter used in Microsoft's docs.前者较短,但我似乎看到后者在 Microsoft 的文档中使用。 Is the latter the proper way?后者是正确的方法吗?

The Updated .NET Core Event Pattern documentation page states the following:更新的 .NET 核心事件模式文档页面说明如下:

The previous article discussed the most common event patterns.上一篇文章讨论了最常见的事件模式。 .NET Core has a more relaxed pattern. .NET Core 有更宽松的花纹。 In this version, the EventHandler definition no longer has the constraint that TEventArgs must be a class derived from System.EventArgs.在此版本中,EventHandler 定义不再具有 TEventArgs 必须是从 System.EventArgs 派生的 class 的约束。

Note, however, that if your class is designed to pass data to the event subscribers, you should still follow the naming convention and add the Args suffix (or EventArgs suffix if you derive from EventArgs ).但是请注意,如果您的 class 旨在将数据传递给事件订阅者,您仍应遵循命名约定并添加Args后缀(或EventArgs后缀,如果您从EventArgs派生)。

You can, however, choose not to create a specific class just for event args, if all the data you want to to pass on to the event subscribers is a class you already have.但是,如果您要传递给事件订阅者的所有数据都是您已经拥有的 class,您可以选择不仅为事件参数创建特定的 class。

Yes, the latter is preferred as it makes for more descriptive callback method signatures.是的,后者是首选,因为它可以提供更具描述性的回调方法签名。 EG例如

class FooBarEventObserver
{
   public void OnCreated(object sender, FooBarCreatedEventArgs args)
   {
     ....
   }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM