[英]How to count how many listeners are hooked to an event?
Assuming I have declared假设我已经声明
public event EventArgs<SyslogMessageEventArgs> MessageReceived;
public int SubscribedClients
{
get [...]
}
I would like to count how many "subscribed clients" my class has.我想计算我的班级有多少“订阅客户”。 I need to sum those that subscribed over network though my APIs (not shown in the fragment) plus those that did
channel.MessageReceived+=myMethod;
我需要将通过网络订阅的 API(未显示在片段中)与那些订阅
channel.MessageReceived+=myMethod;
API 相加channel.MessageReceived+=myMethod;
. .
I know that C# events may be declared explicitly with add
and remove
statements, and there I can surely count + or -1 to a local counter, but I never wrote code for explicit events in C#, so I don't know exactly what more to perform on add and remove rather than updating the counter.我知道可以使用
add
和remove
语句显式声明 C# 事件,并且我肯定可以将 + 或 -1 计数到本地计数器,但我从未在 C# 中为显式事件编写代码,所以我不知道还有什么执行添加和删除而不是更新计数器。
Thank you.谢谢你。
您可以使用GetInvocationList()
:
MessageReceived?.GetInvocationList().Length
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 += ...;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.