如何获取添加和删除块中的事件订阅者数量? [英] How do I get the number of event subscribers in the add and remove blocks?
本文介绍了如何获取添加和删除块中的事件订阅者数量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我使用显式语法来声明一个事件,是否可以获得 中的订阅者数量 add {}
和删除{}
代码块?例如:
If I use the explicit syntax for declaring an event, is it possible to get the number of subscribers inside the add {}
and remove {}
code blocks? For example:
public event EventHandler MyEvent
{
add
{
MyEvent += value;
// Can I get a count of subscribers here?
}
remove
{
MyEvent -= value;
// And also here?
}
}
我的尝试:
我已经找到了在代码的其他部分执行此操作的方法,使用...
What I have tried:
I have found a way to do this in other parts of the code, using...
MyEvent.GetInvocationList().Count
...但是我无法弄清楚如何在事件声明代码中使用这种语法。
...but I can't figure out how or even if this syntax can be used inside the event declaration code.
推荐答案
这个怎么样?
How about this?
private EventHandler _myEvent;
private int _myEventSubscribersCount;
public event EventHandler MyEvent
{
add
{
_myEvent += value;
_myEventSubscribersCount = _myEvent.GetInvocationList().Length;
}
remove
{
_myEvent -= value;
_myEventSubscribersCount = _myEvent.GetInvocationList().Length;
}
}
您只能在创建事件的类中执行此操作:
You can only do it from within the class that creates the event:
public class MyClass
{
public event EventHandler MyEvent;
protected virtual void OnMyEvent(EventArgs e)
{
EventHandler eh = MyEvent;
if (eh != null)
{
eh(this, e);
}
}
public int CountEvents()
{
return MyEvent.GetInvocationList().Length;
}
}
...
private void MyButton_Click(object sender, EventArgs e)
{
MyClass mc = new MyClass();
mc.MyEvent += mc_MyEvent;
Console.WriteLine(mc.CountEvents());
mc.MyEvent += mc_MyEvent;
Console.WriteLine(mc.CountEvents());
这篇关于如何获取添加和删除块中的事件订阅者数量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文