How do closures work behind the scenes? (C#)

前端 未结 4 982
挽巷
挽巷 2020-11-27 14:41

I feel I have a pretty decent understanding of closures, how to use them, and when they can be useful. But what I don\'t understand is how they actually work behind the sce

4条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-27 15:20

    Your third guess is correct. The compiler will generate code like this:

    private class Locals
    {
      public int count;
      public void Anonymous()
      {
        this.count++;
      }
    }
    
    public Action Counter()
    {
      Locals locals = new Locals();
      locals.count = 0;
      Action counter = new Action(locals.Anonymous);
      return counter;
    }
    

    Make sense?

    Also, you asked for comparisons. VB and JScript both create closures in pretty much the same way.

提交回复
热议问题