C# 캡처 변수

Featured image

Git Source


static void Main(string[] args)
{
    var actions = new List<Action>();

    for (int idx = 0; idx < 5; idx++)
    { 
        actions.Add(() => Console.WriteLine(idx));
    }

    foreach (var action in actions)
    {
        action.Invoke();
    }
}
static void Main(string[] args)
{
    var actions = new List<Action>();

    for (int idx = 0; idx < 5; idx++)
    { 
        int temp = idx;
        actions.Add(() => Console.WriteLine(temp));
    }

    foreach (var action in actions)
    {
        action.Invoke();
    }
}
class ComplierClass
{
    public int _i;
 
    public void _method()
    {
        Console.WriteLine(_i);
    }
}
 
static void Main(string[] args)
{  
    var actions = new List<Action>();
 
    ComplierClass complier = new ComplierClass();
 
    for (int complier._i = 0; complier._i < 5; complier._i++)
    {  
        actions.Add(complier._method);
    }
 
    foreach(var act in actions)
    {
        act.Invoke();
    }
}
class ComplierClass
{
    public int _temp;
 
    public void _method()
    {
        Console.WriteLine(_temp);
    }
}
 
static void Main(string[] args)
{  
    var actions = new List<Action>(); 
 
    for (int idx = 0; idx < 5; idx++)
    {  
        ComplierClass complier = new ComplierClass();
        complier._temp = i;
        actions.Add(complier._method);
    }
 
    foreach(var act in actions)
    {
        act.Invoke();
    }
}

Reference

Codeproject Inside C# 2.0 Anonymous Methods

.NET Framework: 523. C# 람다(Lambda)에서 변수 캡쳐 방식