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

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

    Thanks @HenkHolterman. Since it was already explained by Eric, I added the link just to show what actual class the compiler generates for closure. I would like to add to that the creation of display classes by C# compiler can lead to memory leaks. For example inside a function there a int variable that is captured by a lambda expression and there another local variable that simply holds a reference to a large byte array. Compiler would create one display class instance which will hold the references to both the variables i.e. int and the byte array. But the byte array will not be garbage collected till the lambda is being referenced.

提交回复
热议问题