简体   繁体   中英

In C#, how can a closure reference itself?

In C#, how can a closure reference itself? The use case is to automatically unsubscribe from an event, after a single occurrence (or on some condition). I know you can create an instance of a delegate, but I'd really like to keep this as a closure, to maintain context. For example:

var someVar = new FooBar();
textBox1.TextChanged += (s, e) => {
    doSomething(someVar);
    // Unsubscribe from further events
    // textBox1.TextChanged -= myself?
    // If I don't unsubscribe, I'm needlessly keeping reference
    // to someVar, and I don't intend to keep triggering this code
    // upon further events.
};

As far as I know it cannot reference itself directly. However, you do something like this instead:

var someVar = new FooBar();
EventHandler closure = null;
closure = (s, e) => {
    doSomething(someVar);
    // Unsubscribe from further events
    // textBox1.TextChanged -= myself?
    // If I don't unsubscribe, I'm needlessly keeping reference
    // to someVar, and I don't intend to keep triggering this code
    // upon further events.
    textBox1.TextChanged -= closure;
};
textBox1.TextChanged += closure;

Credit: Can an anonymous method in C# call itself?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM