Problem with delegates in C#

后端 未结 4 1023
慢半拍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.

提交回复
热议问题