Problem with delegates in C#

后端 未结 4 1024
慢半拍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:18

    The problem is that you're capturing the same variable i in every delegate - which by the end of the loop just has the value 5.

    Instead, you want each delegate to capture a different variable, which means declaring a new variable in the loop:

    for (int i = 0; i < 5; ++i)
    {
        int localCopy = i;
        methods.Add(delegate(object obj) { return DummyMethod(localCopy); });
    }
    

    This is a pretty common "gotcha" - you can read a bit more about captured variables and closures in my closures article.

    0 讨论(0)
  • 2021-02-06 09:21

    I think it is because the variable i is put to the heap (it's a captured variable)

    Take a look at this answer.

    0 讨论(0)
  • 2021-02-06 09:25

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

    private static void Method2()
    {
        List<Methodx> list = new List<Methodx>();
        Methodx item = null;
        <>c__DisplayClassa classa = new <>c__DisplayClassa();
        classa.i = 0;
        while (classa.i < 5)
        {
            if (item == null)
            {
                item = new Methodx(classa.<Method2>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 <Method2>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.

    0 讨论(0)
  • 2021-02-06 09:29

    This article will probably help you understand what is happening (i.e. what a closure is): http://blogs.msdn.com/oldnewthing/archive/2006/08/02/686456.aspx

    0 讨论(0)
提交回复
热议问题