1

Possible Duplicate:
Unsubscribe anonymous method in C# How do I Unregister 'anonymous' event handler

Ok, lets say I have the following code:

    private void AttachEvent(AwesomeObject someObject)
    {
        int id = GetCurrentIdValue();
        someUnknownClass.SomeEvent += () => someObject.CreateAwesomeness(id);
    }

(essentially, I'm just trying to illustrate the need to use a local variable in an event handler as suggested in this thread). From a memory management standpoint, I can't just detach from someUnknownClass.SomeEvent because I don't have a handle on the handler. Further, let's assume someUnknownClass is a third party type, so I can't add any code within that class to detach the event internally as suggested.

My question is, how do I avoid a memory leaks while still being able to use anonymous methods as event handlers?

4

1 に答える 1

0

あなたがそれらを使う方法ではなく、それは不可能です。あなたができることは、そのメソッドを変数に割り当て、その変数を使用した後、 +-fromイベントに割り当てることです。しかし、このようにして、クロージャが通常あなたに与える「自然な」感覚を失うでしょう。

于 2012-04-11T20:29:16.340 に答える