Visual Basic具有自定义事件。自定义事件的示例:https://msdn.microsoft.com/en-us/library/wf33s4w7.aspx

有没有办法在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#中有没有办法做到这一点?

换句话说/一个稍微不同的问题:是否可以在事件的订阅和取消订阅上运行代码?

最佳答案

您还可以通过在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
    }
}

关于c# - C#中类似于VB的自定义事件,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43517146/

10-13 07:46
查看更多