C# 显式删除事件处理程序 [英] C# Explicitly Removing Event Handlers
问题描述
我想知道将对象设置为 null 是否会清除附加到对象事件的任何事件处理程序...
I was wondering if setting an object to null will clean up any eventhandlers that are attached to the objects events...
例如
Button button = new Button();
button.Click += new EventHandler(Button_Click);
button = null;
button = new Button();
button.Click += new EventHandler(Button_Click);
button = null;
等等...
这会导致内存泄漏吗?
推荐答案
如果在任何地方都没有其他对 button
的引用,那么这里不需要移除事件处理程序以避免内存泄漏.事件处理程序是单向引用,因此只有在具有事件的对象长期存在时才需要删除它们,并且您希望避免处理程序(即具有处理程序方法的对象)的存活时间超过它们应该.在您的示例中,情况并非如此.
If there are no other references to button
anywhere, then there is no need to remove the event handler here to avoid a memory leak. Event handlers are one-way references, so removing them is only needed when the object with events is long-lived, and you want to avoid the handlers (i.e. objects with handler methods) from living longer than they should. In your example, this isn't the case.
这篇关于C# 显式删除事件处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!