【发布时间】:2020-10-13 11:55:14
【问题描述】:
我是 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);
}
}
对我来说,这个命名根本没有意义,或者我不明白事件在 C# 中是如何工作的。如果我没有错,那么在 DoSomething 中触发了 CustomEvent。但通常 onAnything 函数正在监听事件。您是否也认为 OnRaiseCustomEvent 应该命名为 RaiseCustomEvent?
【问题讨论】:
标签: c# events publish-subscribe