我认为对于C#方法的前缀"On“的用法有很大的混淆。
在MSDN文章“处理和引发事件”https://msdn.microsoft.com/en-us/library/edzehd2t(v=vs.110).aspx中,它说,
通常,要引发事件,需要添加标记为受保护和虚拟(在C#中)或被保护和覆盖(在Visual中)的方法。将此方法命名为OnEventName;例如,OnDataReceived。该方法应该接受一个指定事件数据对象的参数。提供此方法可使派生类重写引发事件的逻辑。派生类应始终调用基类的OnEventName方法,以确保已注册的委托接收事件。
指示开..。方法是引发事件。但是,在许多编码示例中,甚至在Microsoft提供的一些示例中,我们可以看到事件--用作事件处理程序的On方法,如此处的https://msdn.microsoft.com/en-us/windows/uwp/gaming/tutorial--adding-move-look-controls-to-your-directx-game?f=255&MSPPError=-2147217396中的on。
首先,让我们填充鼠标和触摸指针事件处理程序。在第一个事件处理程序OnPointerPressed(),中,我们从CoreWindow获得指针的x坐标,当用户单击鼠标或触摸外观控制器区域中的屏幕时,该坐标管理我们的显示。
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;
}
}
}我的问题是:
发布于 2016-11-25 15:19:18
对于引发事件的类:当“某些条件”发生时,调用该类中的方法OnSomeCondition()是有意义的。然后,如果您想将此条件通知外部方,那么您将在OnSomeCondition()方法中引发一个事件OnSomeCondition()。
对于处理该事件的类:当Visual自动生成处理程序方法时,它将其命名为someClass_SomeCondition (至少在C#中是这样的,这就是您标记问题的内容)。第二个文档使用的不是C#,这可能解释了两者之间的区别(我不知道事件处理程序是否有“正式”命名约定)。
但是,当您从引发事件的类继承,并且基类遵循了protected virtual建议时,' event‘这个词就变得模棱两可:您仍然可以处理SomeCondition事件,但也可以选择覆盖OnSomeCondition()方法。
因此,我不会说On前缀“用于引发事件”,而是“处理条件”,您可以选择在OnCondition()方法中引发事件--对于消费端,您可以处理事件或重写OnCondition()行为。这也是第一份文件所指出的:
提供此方法可使派生类重写引发事件的逻辑。
https://stackoverflow.com/questions/40807647
复制相似问题