Integer handled as reference type when passed into a delegate

后端 未结 4 1298
面向向阳花
面向向阳花 2020-12-21 05:25

I was attending the TechDays 2013 in the Netherlands this week and I got an interesting quiz question presented. The question was: What is the output of the following progra

4条回答
  •  粉色の甜心
    2020-12-21 06:07

    In your case, the delegated methods are anonymous methods accessing a local variable (the for loop index i). That is, these are clousures.

    Since the anonymous method is called ten times after the for loop, it gets the most recent value for i.

    A simple sample of various clousures accessing the same reference

    Here's a simplified version of clousure behavior:

    int a = 1;
    
    Action a1 = () => Console.WriteLine(a);
    Action a2 = () => Console.WriteLine(a);
    Action a3 = () => Console.WriteLine(a);
    
    a = 2;
    
    // This will print 3 times the latest assigned value of `a` (2) variable instead
    // of just 1. 
    a1();
    a2();
    a3();
    

    Check this other Q&A (What are clousures in .NET?) on StackOverflow for more info about what are C#/.NET clousures!

提交回复
热议问题