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

前端 未结 6 1526
南笙
南笙 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条回答
  •  萌比男神i
    2020-11-30 12:16

    It happens because of the way C# passes parameters to a lambda. It wraps the variable access in a class which is created during compilation, and exposes it as a field to the lambda body.

提交回复
热议问题