闭包

List lst = new List();
for(int i=0; i<5; i++)
{
    // wrong, output:55555
    Action act = ()=>Console.WriteLine(i);
    
    // correct, output:01234
    /*
    int temp = i;
    Action act = ()=>Console.WriteLine(temp);
    */

    lst.Add(act);
}
foreach(var fun in lst)
{
    fun();
}

你可能感兴趣的:(闭包)