获取事件被注册的次数

刚才看了Artech的也谈事件的文章,文章地址:http://www.cnblogs.com/artech/archive/2010/07/10/1774833.html,他在这篇文章中讲到了MulticastDelegate 类,他说事件本质上是一个MulticastDelegate对象,由此我想到使用MulticastDelegate 类来获取一个事件被注册的次数,下面是我写的一个测试类来测试MulticastDelegate 能否来获取事件被注册的次数,结果是可以获取的,代码如下:

 

代码
class Program
{
static void Main(string[] args)
{
EventCountTest a
= new EventCountTest();
a.Print
+= new EventHandler(Event1);
a.Print
+= new EventHandler(Event2);
a.Print
+= new EventHandler(Event2);
//调用次方法将触发事件
a.Invok();
}

static void Event1(object sender, EventArgs e)
{
Console.WriteLine(
"Event1");
}
static void Event2(object sender, EventArgs e)
{
Console.WriteLine(
"Event2");
}
static void Event3(object sender, EventArgs e)
{
Console.WriteLine(
"Event3");
}
}
/// <summary>
/// 定义一个用来测试事件被注册次数的类
/// </summary>
public class EventCountTest
{
public event EventHandler Print;
//模拟事件被调用
public void Invok()
{
if (Print != null)
{
//打印事件被注册的次数
Console.WriteLine((Print as MulticastDelegate).GetInvocationList().Count().ToString());
Print(
this,new EventArgs());
}
}
}

 有一点要注意的是,只能在类内部获取该事件被注册的次数

原文地址:https://www.cnblogs.com/dagehaoshuang/p/1774896.html