C#中的委托问题 [英] Problem with delegates in C#

查看:120
本文介绍了C#中的委托问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的程序中,DummyMethod总是打印5.但是如果我们使用注释的代码,我们得到不同的值(即1,2,3,4)。任何人都可以解释为什么会发生这种情况?

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 happenning?

        delegate int Methodx(object obj);

        static int DummyMethod(int i)
        {
            Console.WriteLine("In DummyMethod method i = " + i);
            return i + 10;
        }

        static void Main(string[] args)
        {    
            List<Methodx> methods = new List<Methodx>();

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

            //methods.Add(delegate(object obj) { return DummyMethod(1); });
            //methods.Add(delegate(object obj) { return DummyMethod(2); });
            //methods.Add(delegate(object obj) { return DummyMethod(3); });
            //methods.Add(delegate(object obj) { return DummyMethod(4); });

            foreach (var method in methods)
            {
                int c = method(null);
                Console.WriteLine("In main method c = " + c);
            }
        }

此外,如果使用以下代码,

Also if the following code is used, I get the desired result.

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


推荐答案

问题是,在每个代理中捕获相同的变量 i - 在循环结束时只有值5。

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); });
}

这是一个很常见的getcha捕获的变量和关闭。我的关闭文章

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

这篇关于C#中的委托问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆