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

前端 未结 4 992
挽巷
挽巷 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:04

    The compiler (as opposed to the runtime) creates another class/type. The function with your closure and any variables you closed over/hoisted/captured are re-written throughout your code as members of that class. A closure in .Net is implemented as one instance of this hidden class.

    That means your count variable is a member of a different class entirely, and the lifetime of that class works like any other clr object; it's not eligible for garbage collection until it's no longer rooted. That means as long as you have a callable reference to the method it's not going anywhere.

提交回复
热议问题