【Unity】【CSharp】闭包

原因:引用的是地址,而不是值

1
2
3
4
5
6
7
8
9
10
11
12
13
14
static void Main(string[] args)
{
Action[] actions = new Action[3];
for (int i = 0; i < 3; i++)
{
actions[i] = () => Console.WriteLine(i); // 该委托保存的是i的地址
}

foreach (var action in actions)
{
// 输出i的地址的值
action(); // 输出 3 3 3,而不是 0 1 2
}
}