众所周知,我们可以创建一个EventHandler并向其添加N次次数.喜欢:
// Declare and EventHandler public event EventHandler InternetConnectionAvailableEvent; private void OnInternetConnectionAvailableEvent() { if (InternetConnectionAvailableEvent != null) { EventHandler handle = InternetConnectionAvailableEvent; EventArgs e = EventArgs.Empty; handle(this,e); } } // IN OTHER CLASS WHERE I USE THE EVENT // Set the method name to handle the event monitorInternet.InternetConnectionAvailableEvent += HandleInternetConnectionEvent; void HandleInternetConnectionEvent(object sender,EventArgs e) { if (syncContext != null) { MonitorInternetConnection mic = (MonitorInternetConnection)sender; if (mic != null) { syncContext.Post(o => InternetConnected(),null); } } } // To remove monitorInternet.InternetConnectionAvailableEvent -= null;
更新:
// To remove it should be monitorInternet.InternetConnectionAvailableEvent -= HandleInternetConnectionEvent; // CORRECT
如果我做了monitorInternet.InternetConnectionAvailableEvent – = null;所有的事件处理程序都被删除.我的意思是如果它设置2-3次,并删除一次,通过使其为null,所有其他方法将被自动删除.
我相信会的,但我只想与你确认专家.而谷歌搜索我没有得到我需要的满意答案.
如果错了,请更正我
解决方法
要查找事件处理程序的数量,可以使用以下代码:
InternetConnectionAvailableEvent.GetInvocationList().Length;
以下代码演示了MyEvent – = null不会清除处理程序列表.
public static event EventHandler MyEvent; [STAThread] static void Main() { MyEvent += (s,dea) => 1.ToString(); MyEvent -= null; Console.WriteLine(MyEvent.GetInvocationList().Length); // Prints 1 MyEvent = null; Console.WriteLine(MyEvent == null); // Prints true }
要清除列表(这可能永远不是一个好主意),您可以将事件设置为null(只要您在声明事件的类中).