C# Closures, why is the loopvariable captured by reference?

前端 未结 6 1522
南笙
南笙 2020-11-30 11:39

In this example, I\'m attempting to pass by value, but the reference is passed instead.

for (int i = 0; i < 10; i++)
{
    Thread t = new Thread(() =>         


        
6条回答
  •  無奈伤痛
    2020-11-30 12:17

    You definitely want to read Eric Lippert's "Closing over the loop variable considered harmful":

    • Part 1
    • Part 2

    In Short: The behavior you see is exactly how C# works.

提交回复
热议问题