王凯越*_*ang 5 c# events msdn coding-style event-handling
我认为使用“ On”作为C#方法的前缀存在很大的困惑。
在MSDN文章“处理和引发事件” https://msdn.microsoft.com/zh-cn/library/edzehd2t(v=vs.110).aspx中,它说:
通常,要引发一个事件,您可以添加一个标记为protected and virtual(在C#中)或Protected and Overridable(在Visual Basic中)的方法。将此方法命名为OnEventName;例如OnDataReceived。该方法应采用一个指定事件数据对象的参数。您提供此方法以使派生类可以重写引发事件的逻辑。派生类应始终调用基类的OnEventName方法,以确保已注册的委托接收事件。
表示On ...方法将引发一个事件。但是,在许多编码示例中,即使Microsoft提供了一些示例,我们也可以看到事件On方法用作事件处理程序,例如此处的https://msdn.microsoft.com/zh-cn/windows/uwp/gaming/tutorial -将移动控件控件添加到您的Directx游戏中?f = 255&MSPPError = -2147217396
首先,让我们填充鼠标和触摸指针事件处理程序。在第一个事件处理程序OnPointerPressed()中,我们从CoreWindow获取指针的xy坐标,当用户单击鼠标或触摸外观控制器区域中的屏幕时,该CoreWindow管理我们的显示。
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;
}
}
}
Run Code Online (Sandbox Code Playgroud)
我的问题是:
对于引发事件的类:当“某些条件”发生时,调用OnSomeCondition()该类中的方法是有意义的。然后,如果您想通知外部方有关此情况的信息,您将SomeCondition在该OnSomeCondition()方法中引发一个事件。
对于处理事件的类:当 Visual Studio 自动生成处理程序方法时,它会调用它someClass_SomeCondition(至少在 C# 中,这就是您标记问题的方法)。不过,第二个文档摘录和示例不是 C#,这可以解释其中的差异(我不知道事件处理程序是否有“官方”命名约定)。
但是,当您从引发事件的类继承并且基类已遵循建议时protected virtual,“事件”一词变得不明确:您仍然可以处理SomeCondition事件,但也可以选择重写该OnSomeCondition()方法。
因此,我不会说On前缀“用于引发事件”,而是“用于处理条件”,并且您可以选择在方法中引发事件OnCondition()- 对于消费端,您可以处理事件或覆盖行为。OnCondition() 这也是第一个文档摘录所说的内容:
您提供此方法以使派生类能够重写引发事件的逻辑。