验证 C# 事件触发器函数的命名

Verify naming of C# event trigger functions

我是 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# 命名约定。
您不必同意它,但您应该熟悉它,我也建议在您的代码中使用它。

一位经验丰富的 c# 程序员会看到一个名为 On<blabla> 的方法,该方法接收名为 EventArgs 的参数或任何以后缀 EventArgs 结尾的参数(如 <blabla>EventArgs ) 将立即期望此方法引发名为 <blabla>.
的事件 (当然,<blabla>只是一个实际名称的占位符)

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

中所述

... events are a special type of delegate that can only be invoked from within the class that declared them. Derived classes cannot directly invoke events that are declared within the base class.

这就是为什么你需要 On<blabla>(BlaBlaEventArgs e) 方法是 protected virtual(除非你的 class 被声明为 sealed) - 所以它是派生的 classes 也将能够引发 <blabla> 事件。

官方文档也承认(至少部分)在此模式中选择的名称有些误导 - as mentioned here:

The name EventHandler can lead to a bit of confusion as it doesn't actually handle the event.

就我个人而言,我认为他们可能为此以及 On<blabla> 方法选择了更好的名称,但现在改变它已经太晚了。