Всем привет.
Известная проблема:
| Скрытый текст |
| using System;
namespace capttest1
{
class Program
{
static void Main(string[] args)
{
new Program().Test();
}
private void Test()
{
var items = new[] { "1", "2", "3", "4", "5" };
var index = 0;
foreach (var item in items)
{
_actions[index] = () => Console.WriteLine(item);
index++;
}
foreach (var action in _actions)
{
action();
}
}
Action[] _actions = new Action[5];
}
}
|
| |
Код выведет:
5
5
5
5
5
Но почему такой код работает, как нужно:
| Скрытый текст |
| using System;
namespace capttest1
{
class Program
{
static void Main(string[] args)
{
new Program().Test();
}
private void Test()
{
var items = new[] { "1", "2", "3", "4", "5" };
var index = 0;
foreach (var item in items)
{
SaveAction(item, index);
index++;
}
foreach (var action in _actions)
{
action();
}
}
private void SaveAction(string item, int index)
{
_actions[index] = () => Console.WriteLine(item);
}
Action[] _actions = new Action[5];
}
}
|
| |
Выводит:
1
2
3
4
5