Problem with delegates in C#

后端 未结 4 1015
慢半拍i
慢半拍i 2021-02-06 08:29

In the following program, DummyMethod always print 5. But if we use the commented code instead, we get different values (i.e. 1, 2, 3, 4). Can anybody please explain why this is

4条回答
  •  清歌不尽
    2021-02-06 09:25

    If you look at the code generated (using Reflector) you can see the difference:

    private static void Method2()
    {
        List list = new List();
        Methodx item = null;
        <>c__DisplayClassa classa = new <>c__DisplayClassa();
        classa.i = 0;
        while (classa.i < 5)
        {
            if (item == null)
            {
                item = new Methodx(classa.b__8);
            }
            list.Add(item);
            classa.i++;
        }
        foreach (Methodx methodx2 in list)
        {
            Console.WriteLine("In main method c = " + methodx2(null));
        }
    }
    

    When you use the initial code it creates a temporary class in the background, this class holds a reference to the "i" variable, so as per Jon's answer, you only see the final value of this.

    private sealed class <>c__DisplayClassa
    {
        // Fields
        public int i;
    
        // Methods
        public <>c__DisplayClassa();
        public int b__8(object obj);
    }
    

    I really recommend looking at the code in Reflector to see what's going on, its how I made sense of captured variables. Make sure you set the Optimization of the code to ".NET 1.0" in the Option menu, otherwise it'll hide all the behind scenes stuff.

提交回复
热议问题