本文介绍了C#知道有多少事件处理器设置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家都知道,我们可以创建一个事件处理程序和方法添加到它的N次。这样的:

As we all know, we can create an EventHandler and add methods to it N number of times. Like:

   // 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



同样的方法可以不删除它被多次调用。

Same method can be called multiple times without removing it.

如果我让 monitorInternet.InternetConnectionAvailableEvent - = NULL; ,所有的事件处理程序被删除。我的意思是,如果它被设置2-3次,并除去只有一次,通过使其为空,也所有其他方法将被自动移除。

If I make monitorInternet.InternetConnectionAvailableEvent -= null;, all the event handlers be removed. I mean if it is set 2-3 times, and removed only once, by making it null, also all the other methods will be removed automatically.

我相信会,但我只是想与各位专家进行确认。虽然谷歌搜索我没有得到我需要的满意的答复。

I believe it will, but I just wanted to confirm with you experts. While googling I didn't get my required satisfactory answer.

如果说错了请纠正我。

推荐答案

要找到事件处理程序的数量,您可以使用此代码:

To find the number of event handlers, you can use this code:

InternetConnectionAvailableEvent.GetInvocationList().Length;



下面的代码演示了 MyEvent - = NULL 不清除处理程序的列表

The following code demonstrates that MyEvent -= null does not clear the list of handlers.

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(只要你在声明事件的类)。

To clear the list (which is probably never a good idea), you can set the event to null (as long as you are in the class that declared the event).

这篇关于C#知道有多少事件处理器设置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 13:46