问题描述
众所周知,我们可以创建一个 EventHandler 并向其添加方法 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#知道设置了多少个EventHandlers?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!