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

前端 未结 6 1536
南笙
南笙 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:02

    Well, that's just how C# works. The lambda expression in your statement constructs a lexical closure, which stores a single reference to i that persists even after the loop has concluded.

    To remedy it, you can do just the thing that you did.

    Feel free to read more on this particular issue all around the Web; my choice would be Eric Lippert's discussion here.

提交回复
热议问题