2017-04-20 52 views
1

Visual Basic具有自定義事件。自定義事件的示例:https://msdn.microsoft.com/en-us/library/wf33s4w7.aspxC中的類VB自定義事件#

有沒有辦法在C#中創建自定義事件?

在我的情況下,我需要創建一個的主要原因是在事件首次訂閱時運行代碼,目前這看起來是不可能的。

例如,假設我有一個按鈕。如果沒有訂戶,我希望此按鈕被禁用(灰色),並且只要有至少一個訂戶即可啓用。從理論上講,我將能夠做這樣的 - 如果這句法確實存在:

// internal event, used only to simplify the custom event's code 
// instead of managing the invocation list directly 
private event Action someevent; 

// Pseudo code ahead 
public custom event Action OutwardFacingSomeEvent 
{ 
    addhandler 
    { 
     if (someevent == null || someevent.GetInvocationList().Length == 0) 
      this.Disabled = false; 
     someevent += value; 
    } 
    removehandler 
    { 
     someevent -= value; 
     if (someevent == null || someevent.GetInvocationList().Length == 0) 
      this.Disabled = true; 
    } 
    raiseevent() 
    { 
     // generally shouldn't be called, someevent should be raised directly, but let's allow it anyway 
     someevent?.Invoke(); 
    } 
} 

如果我理解VB文章正確的,這行代碼換行轉換爲VB,會做正是我想要的。有什麼辦法在C#中做到這一點?

換句話說/一個稍微不同的問題:有沒有辦法在訂閱和取消訂閱事件上運行代碼?

+4

這是您的意思嗎? https://msdn.microsoft.com/en-us/library/bb882534.aspx – Crowcoder

+0

是的。不管我搜索的是什麼,谷歌都沒有提出這個問題。謝謝! – NeatNit

回答

4

您也可以通過在C#中定義顯式事件訪問器來接管事件的訂閱過程。以下是您示例中someevent事件的手動實現:

private Action someevent; // Declare a private delegate 

public event Action OutwardFacingSomeEvent 
{ 
    add 
    { 
     //write custom code 
     someevent += value; 
    } 
    remove 
    { 
     someevent -= value; 
     //write custom code 
    } 
}