我認爲在使用「On」作爲C#方法的前綴方面存在相當混亂。在C#編碼的事件情況下,前綴「On」實現了什麼?
在MSDN文章「處理和引發事件」 https://msdn.microsoft.com/en-us/library/edzehd2t(v=vs.110).aspx它說,
通常,引發一個事件,您可以添加標記爲 保護和虛擬的(在C#)或受保護的方法和Overridable(在Visual Basic中)。將此方法命名爲OnEventName;例如,OnDataReceived。方法 應該帶有一個指定事件數據對象的參數。 您提供此方法以使派生類能夠覆蓋用於引發事件的邏輯 。派生類應始終調用基類的OnEventName方法 以確保註冊的 代表接收事件。
指示On ...方法是引發一個事件。然而,許多編碼樣本,甚至一些由微軟提供的,我們可以看到事件作爲事件處理程序上的方法,就像在這裏https://msdn.microsoft.com/en-us/windows/uwp/gaming/tutorial--adding-move-look-controls-to-your-directx-game?f=255&MSPPError=-2147217396
首先,讓我們填充的鼠標和觸摸指針事件處理程序。在 第一個事件處理程序,OnPointerPressed(),我們得到的指針的X-Y座標 從當用戶點擊鼠標或觸摸在 外觀控制器區域屏幕管理我們的 顯示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;
}
}
}
我的問題是:
- 到底有沒有這樣的歧義超過 「on」 前綴的使用,或只是我的誤解?人們是否真的在使用「On」籌集和處理事件方法?
- 什麼是實施方法籌集和處理事件的標準樣式?什麼是流行的風格?你建議的風格是什麼?
儘管我個人認爲這是一個有趣的問題,應該把這個問題視爲題外話?正如所使用的標籤「編碼風格」的描述已經說過的那樣,它是一個完全自以爲是的主題,並且該標籤不應該再被使用,因爲它是無關緊要的。因爲我對此不確定,所以我沒有舉起一面旗幟,但我希望看到有人爲我解釋/闡述這一點。沒有找到任何有用的元素。但http://codereview.stackexchange.com/可能是這個問題的正確地方? –
我相信這是一個有效的問題,但OP已經混淆了編碼風格和慣用模式。前者是主觀的,後者不是。使用受保護的虛擬'OnEvenName'方法來引發事件確實是一種慣用模式,應該遵循它(請參閱http://stackoverflow.com/q/756237/11683和/或https://msdn.microsoft.com/en-我們/庫/ hy3sefw3.aspx)。現在,命名事件*處理程序*(在事件源外部)「OnEventName」將更多地是編碼風格而不是模式,並且這是一個(稍微令人困惑的)巧合,它們最終命名相同。 – GSerg
您引用了一篇根本不使用.NET *的文章*。因此,不完全適用於.NET約定。它也是事件處理程序方法,不是事件,也不是引發事件的方法。你已經知道了正確的MSDN頁面,第一個鏈接,所以就使用它。 –