Che*_*hen 24
假设该类位于第三方库中,并且无法修改:
public class Data
{
public event EventHandler OnSave;
//other members
}
Run Code Online (Sandbox Code Playgroud)
在你的程序中:
Data d = new Data();
d.OnSave += delegate { Console.WriteLine("event"); };
var handler = typeof(Data).GetField("OnSave", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(d) as Delegate;
if (handler == null)
{
//no subscribers
}
else
{
var subscribers = handler.GetInvocationList();
//now you have the subscribers
}
Run Code Online (Sandbox Code Playgroud)
您可以检查事件是否为 != null。
顺便说一句,在 C# 中,每次引发事件时都需要进行此检查:
if (TheEvent != null) {
TheEvent(this, e);
}
Run Code Online (Sandbox Code Playgroud)
原因正是为了检查事件是否有任何侦听器。
编辑
由于您无法从类外部访问 TheEvent,您可以实现一个进行检查的方法:
public class TheClass {
public bool HasEventListeners() {
return TheEvent != null;
}
}
Run Code Online (Sandbox Code Playgroud)