gpt4 book ai didi

c# - 从 Protected Virtual Void 方法或直接引发事件有什么不同?

转载 作者:太空狗 更新时间:2023-10-29 22:09:07 31 4
gpt4 key购买 nike

我看了一些教程,我不明白为什么他们会建议从 Virtual Protected 方法而不是直接引发事件,有什么区别?

public delegate void SomethingEventHandler(string s);
public event SomethingEventHandler Something;

public void Main() {

// Raising an event
OnSomething(); // Via method
Something("something"); // Directly
}

protected virtual void OnSomething()
{
Something("something");
}

最佳答案

请参阅“开发类库的设计指南”,Event Design :

Do use a protected virtual method to raise each event. This is applicable only to non-static events on unsealed classes, not to structures, sealed classes, or static events.

Complying with this guideline allows derived classes to handle a base class event by overriding the protected method. The name of the protected virtual (Overridable in Visual Basic) method should be the same as the event name prefixed with On. For example, the protected virtual method for an event named "TimeChanged" is named "OnTimeChanged".

Important

Derived classes that override the protected virtual method are not required to call the base class implementation. The base class must continue to work correctly even if its implementation is not called.

关于c# - 从 Protected Virtual Void 方法或直接引发事件有什么不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34704740/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com