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

验证C#事件触发器函数的命名,c#,events,publish-subscribe,C#,Events,Publish Subscribe,我是C#新手,我在C#中找到了关于事件的文档和示例: 特别是对我来说,以下几行很有意思: 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.

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

特别是对我来说,以下几行很有意思:

    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);
        }
    }
public void DoSomething()
{
//在这里编写一些有用的代码
//然后引发事件。您也可以引发事件
//在执行代码块之前。
OnRaiseCustomEvent(新的CustomEventArgs(“事件触发”);
}
//在受保护的虚拟方法内包装事件调用
//允许派生类重写事件调用行为
受保护的虚拟void OnRaiseCustomEvent(CustomEventArgs e)
{
//制作事件的临时副本,以避免
//最后一个订户取消订阅时的竞争条件
//在空检查之后和引发事件之前。
EventHandler raiseEvent=RaiseCustomEvent;
//如果没有订阅服务器,则事件将为null
如果(raiseEvent!=null)
{
//格式化要在CustomEventArgs参数内发送的字符串
e、 消息+=$“在{DateTime.Now}”;
//打电话提出该事件。
raiseEvent(本,e);
}
}
对我来说,这个命名毫无意义,或者我不理解事件在C#中是如何工作的。如果我没有错,那么在DoSomething中会触发CustomEvent。但通常情况下,任何函数都在监听事件。您是否也认为OnRaiseCustomEvent应该命名为RaiseCustomEvent?

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

一个有经验的c#程序员如果在上看到一个名为
的方法,该方法接受一个名为
EventArgs
的参数,或者任何以后缀
EventArgs
结尾的东西(比如
EventArgs
),就会立即期望该方法引发一个名为
的事件
(当然,
只是实际名称的占位符)

此模式的存在是因为当事件被继承时,引发它们的唯一方法是在声明类型内-如中所述:

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

这就是为什么需要对(BlaBlaEventArgs e)
方法上的
进行
虚拟保护
(除非您的类声明为
密封
)-以便它的派生类也能够引发
事件

官方文件也承认,在这种模式中选择的名称(至少有一些)有些误导:

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

就个人而言,我认为他们可能会为这个方法以及
方法上的
选择更好的名称,但现在改变它已经太晚了