在C#中,闭包如何引用自身?

时间:2015-11-12 19:14:05

标签: c# closures

在C#中,闭包如何引用自身?用例是在一次事件发生后(或在某种情况下)自动取消订阅事件。我知道你可以创建一个委托的实例,但我真的想把它作为一个闭包来保持上下文。例如:

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.
};

1 个答案:

答案 0 :(得分:1)

据我所知,它不能直接引用自己。但是,你做了类似的事情:

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;

信用: Can an anonymous method in C# call itself?