【问题标题】:Verify naming of C# event trigger functions [closed]验证 C# 事件触发函数的命名 [关闭]
【发布时间】:2020-10-13 11:55:14
【问题描述】:

我是 C# 新手,我找到了有关 C# 事件的文档和示例:

https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/events/how-to-publish-events-that-conform-to-net-framework-guidelines

对我来说,尤其是这些台词很有趣:

    public void DoSomething()
    {
        // Write some code that does something useful here
        // then raise the event. You can also raise an event
        // before you execute a block of code.
        OnRaiseCustomEvent(new CustomEventArgs("Event triggered"));
    }

    // Wrap event invocations inside a protected virtual method
    // to allow derived classes to override the event invocation behavior
    protected virtual void OnRaiseCustomEvent(CustomEventArgs e)
    {
        // Make a temporary copy of the event to avoid possibility of
        // a race condition if the last subscriber unsubscribes
        // immediately after the null check and before the event is raised.
        EventHandler<CustomEventArgs> raiseEvent = RaiseCustomEvent;

        // Event will be null if there are no subscribers
        if (raiseEvent != null)
        {
            // Format the string to send inside the CustomEventArgs parameter
            e.Message += $" at {DateTime.Now}";

            // Call to raise the event.
            raiseEvent(this, e);
        }
    }

对我来说,这个命名根本没有意义,或者我不明白事件在 C# 中是如何工作的。如果我没有错,那么在 DoSomething 中触发了 CustomEvent。但通常 onAnything 函数正在监听事件。您是否也认为 OnRaiseCustomEvent 应该命名为 RaiseCustomEvent?

【问题讨论】:

    标签: c# events publish-subscribe


    【解决方案1】:

    这是 c# 的命名约定。
    你不必同意它,但你应该熟悉它,我也建议在你的代码中使用它。

    一个有经验的 c# 程序员会看到一个名为 On&lt;blabla&gt; 的方法,该方法接受一个名为 EventArgs 的参数或任何以后缀 EventArgs 结尾的东西(如 &lt;blabla&gt;EventArgs),他会立即期望这个方法引发一个事件叫&lt;blabla&gt;
    (当然,&lt;blabla&gt; 只是真实姓名的占位符)

    存在这种模式是因为在继承事件时,引发它们的唯一方法是在声明类型中 - 如 How to raise base class events in derived classes (C# Programming Guide) 中所述:

    ... 事件是一种特殊类型的委托,只能从声明它们的类中调用。派生类不能直接调用在基类中声明的事件。

    这就是为什么您需要将 On&lt;blabla&gt;(BlaBlaEventArgs e) 方法设为 protected virtual(除非您的类被声明为 sealed) - 这样它的派生类也能够引发 &lt;blabla&gt; 事件。

    官方文档还承认(至少有一些)在这种模式中选择的名称有些误导 - as mentioned here:

    EventHandler 这个名称可能会导致一些混淆,因为它实际上并不处理事件。

    就个人而言,我认为他们可能为此以及 On&lt;blabla&gt; 方法选择了更好的名称,但现在更改它为时已晚。

    【讨论】:

      猜你喜欢
      • 2014-12-20
      • 2021-07-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多