【问题标题】:How to count how many listeners are hooked to an event?如何计算有多少听众被一个事件所吸引?
【发布时间】:2010-10-30 12:21:28
【问题描述】:

假设我已经声明

public event EventArgs<SyslogMessageEventArgs> MessageReceived;

public int SubscribedClients
{
    get [...]
}

我想计算我的班级有多少“订阅客户”。我需要通过我的 API(未在片段中显示)加上通过网络订阅的那些订阅 channel.MessageReceived+=myMethod;

我知道 C# 事件可以用 addremove 语句显式声明,我当然可以将 + 或 -1 计数到本地计数器,但我从未在 C# 中为显式事件编写代码,所以我不知道在添加和删除而不是更新计数器时还需要​​执行什么操作。

谢谢。

【问题讨论】:

    标签: c# events


    【解决方案1】:

    你可以使用GetInvocationList():

    MessageReceived?.GetInvocationList().Length
    

    【讨论】:

    • 你最好添加一个空测试。
    • 如果使用空委托初始化事件,则无需进行空测试。但是,计数长度将为 1。 public event EventArgs MessageReceived = delegate { };
    • 11 年后:我想指出 ?. 是 C# 中的空测试(读作 if not null
    • @darkpbj 我的答案是在 2019 年编辑的 :-D 所以看起来 cmets 跑调了。
    【解决方案2】:
    class A
    {
       public event EventArgs<SyslogMessageEventArgs> MessageReceived;
    
       public int SubscribedClients
       {
           get {
             return (MessageReceived == null)
                    ? 0
                    : MessageReceived.GetInvocationList().Length
                    ;
           }
       } 
    }
    
    
    void Main()
    {
        A a = new A();
        if(a.SubscribedClients == 0)
        {
            a.MessageReceived += ...;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-02-26
      • 2022-01-22
      • 2013-06-07
      • 2022-12-13
      • 1970-01-01
      • 2012-11-11
      • 2012-04-01
      • 1970-01-01
      相关资源
      最近更新 更多