检查事件是否有任何听众?

use*_*528 16 .net c# clr

是否可以检测事件是否有任何听众?(如果没有人需要,我需要处理我的事件提供者对象)

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)

  • 如果在没有添加OnSave事件时处理程序将为null,则上面的代码应该具有空检查,否则将出错. (2认同)

Sim*_*one 9

您可以检查事件是否为 != 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)