开发者

Delegate reference itself

Is there a way for a delegate to reference itself? I'm looking for a way to do this:

delegate void Foo();
list<Foo> foos;

void test() {
    li开发者_如何学Gost.Add(delegate() {
        list.Remove(/* this delegate */);
    });
}


I'm not sure exactly what you're trying to do, but it's possible for a delegate to reference itself like this:

delegate void Foo();
List<Foo> foos = new List<Foo>();

void test() {
    Foo del = null;
    del = delegate { foos.Remove(del); };

    foos.Add(del);
}


One way is for the delegate to accept an argument for itself:

delegate void Foo(Foo self);
...
list.Add(delegate (Foo self) { list.Remove(self);});
...
foreach (Foo f in list) f(f);

Another way would be to close over a variable refering to itself:

Foo foo;
foo = delegate() { list.Remove(foo);}
list.Add(foo);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜