0

我对这篇文章有疑问:http: //davybrion.com/blog/2009/09/event-subscrition-and-memory-leaks-yet-again/

我在 vb.net 中有事件的内存泄漏。我用内存分析器查看我的应用程序,它说我的问题是事件:-(

现在我找到了这篇文章,我想试试。但我不知道delegate{}in 是什么public event EventHandler<EventArgs> MyEvent = delegate { };意思。

4

2 回答 2

3

It's just an empty event handler, that exists (therefore doesn't need to be checked for null) but does nothing. The following code snippets are basically the same:

// An anonymous delegate (your example):
public event EventHandler<EventArgs> MyEvent = delegate { };

// The same function using Lambda:
public event EventHandler<EventArgs> MyEvent = (sender, e) => { };

// A similar function using a named method:
public event EventHandler<EventArgs> MyEvent = Handler;
private static void Handler(object sender, EventArgs eventArgs) { }

Translated to VB.Net:

Public Class SomeClass
    Public Event MyEvent(ByVal sender As Object, ByVal e As EventArgs)

    // The following sub is the empty delegate
    Private Sub Handler(ByVal sender As Object, ByVal e As EventArgs) _
                        Handles Me.MyEvent
        // empty
    End Sub
End Class
于 2012-09-07T09:49:05.210 回答
1

这只是避免对事件进行空值检查的一种偷偷摸摸的方式;基本上,它使用匿名方法作为初始值,但该方法不做任何事情。作为一个实现细节,这个空的委托实例实际上被缓存在一个静态字段中,因此它不会对每个实例产生巨大的影响。

如果您不想担心{},那么只需将其关闭:

public event EventHandler MyEvent;

并做空检查!

于 2012-09-07T09:47:02.193 回答