c# – 检查事件是否有任何监听器?

前端之家收集整理的这篇文章主要介绍了c# – 检查事件是否有任何监听器?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
是否可以检测事件是否有任何监听器? (我需要处理我的事件提供者对象,如果没有人需要的话)

解决方法

假设课程在第三方库中,无法修改
  1. public class Data
  2. {
  3. public event EventHandler OnSave;
  4. //other members
  5. }

在你的程序中

  1. Data d = new Data();
  2. d.OnSave += delegate { Console.WriteLine("event"); };
  3. var handler = typeof(Data).GetField("OnSave",BindingFlags.NonPublic | BindingFlags.Instance).GetValue(d) as Delegate;
  4.  
  5. if (handler == null)
  6. {
  7. //no subscribers
  8. }
  9. else
  10. {
  11. var subscribers = handler.GetInvocationList();
  12. //now you have the subscribers
  13. }

猜你在找的C#相关文章