是否可以检测事件是否有任何监听器? (我需要处理我的事件提供者对象,如果没有人需要的话)
解决方法
假设课程在第三方库中,无法修改:
- public class Data
- {
- public event EventHandler OnSave;
- //other members
- }
在你的程序中
- 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
- }