我觉得在使用“On”作为C#方法前缀方面存在相当的混淆。
在MSDN文章“处理和引发事件”https://msdn.microsoft.com/en-us/library/edzehd2t(v=vs.110).aspx中,它说:
通常,要引发一个事件,您需要添加一个标记为受保护和虚拟(在C#中)或Protected和Overridable(在Visual Basic中)的方法。将此方法命名为OnEventName;例如,OnDataReceived。该方法应该接受一个参数,指定事件数据对象。您提供此方法以使派生类能够重写引发事件的逻辑。派生类应始终调用基类的OnEventName方法,以确保已注册的委托接收事件。
在MSDN文章“处理和引发事件”https://msdn.microsoft.com/en-us/library/edzehd2t(v=vs.110).aspx中,它说:
通常,要引发一个事件,您需要添加一个标记为受保护和虚拟(在C#中)或Protected和Overridable(在Visual Basic中)的方法。将此方法命名为OnEventName;例如,OnDataReceived。该方法应该接受一个参数,指定事件数据对象。您提供此方法以使派生类能够重写引发事件的逻辑。派生类应始终调用基类的OnEventName方法,以确保已注册的委托接收事件。
表明 On... 方法是用于引发事件的。然而,在许多编码示例中,甚至包括 Microsoft 提供的一些示例,我们可以看到 On 方法被用作事件处理程序,例如此处 https://msdn.microsoft.com/en-us/windows/uwp/gaming/tutorial--adding-move-look-controls-to-your-directx-game?f=255&MSPPError=-2147217396
首先,让我们填充鼠标和触摸指针事件处理程序。在第一个事件处理程序 OnPointerPressed() 中,当用户单击鼠标或在查看控制器区域触摸屏幕时,我们从管理我们显示的 CoreWindow 中获取指针的 x-y 坐标。
void MoveLookController::OnPointerPressed(
_In_ CoreWindow^ sender,
_In_ PointerEventArgs^ args)
{
// Get the current pointer position.
uint32 pointerID = args->CurrentPoint->PointerId;
DirectX::XMFLOAT2 position = DirectX::XMFLOAT2( args->CurrentPoint->Position.X, args->CurrentPoint->Position.Y );
auto device = args->CurrentPoint->PointerDevice;
auto deviceType = device->PointerDeviceType;
if ( deviceType == PointerDeviceType::Mouse )
{
// Action, Jump, or Fire
}
// Check if this pointer is in the move control.
// Change the values to percentages of the preferred screen resolution.
// You can set the x value to <preferred resolution> * <percentage of width>
// for example, ( position.x < (screenResolution.x * 0.15) ).
if (( position.x < 300 && position.y > 380 ) && ( deviceType != PointerDeviceType::Mouse ))
{
if ( !m_moveInUse ) // if no pointer is in this control yet
{
// Process a DPad touch down event.
m_moveFirstDown = position; // Save the location of the initial contact.
m_movePointerPosition = position;
m_movePointerID = pointerID; // Store the id of the pointer using this control.
m_moveInUse = TRUE;
}
}
else // This pointer must be in the look control.
{
if ( !m_lookInUse ) // If no pointer is in this control yet...
{
m_lookLastPoint = position; // save the point for later move
m_lookPointerID = args->CurrentPoint->PointerId; // store the id of pointer using this control
m_lookLastDelta.x = m_lookLastDelta.y = 0; // these are for smoothing
m_lookInUse = TRUE;
}
}
}
我的问题是:
- 是否确实存在关于“On”前缀用法的歧义,还是只是我的误解?人们是否真的在引发和处理事件方法中都使用“On”?
- 实现引发和处理事件方法的标准样式是什么?流行的样式有哪些?你建议使用哪种样式?
OnEvenName
方法来引发事件确实是一种惯用模式,应该遵循(请参见https://dev59.com/PHRA5IYBdhLWcg3w_DHF和/或https://msdn.microsoft.com/en-us/library/hy3sefw3.aspx)。现在,将事件*处理程序*(外部于事件源)命名为`OnEventName`更多的是编码风格而不是模式,它是一个(稍微令人困惑的)巧合,它们最终被命名为相同的名称。 - GSerg