2017-04-20 46 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 
    } 
}