C#-For循环和Lambda表达式 [英] C# - For loop and the lambda expressions

查看:488
本文介绍了C#-For循环和Lambda表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题是为什么我在lambda表达式中使用迭代器变量会得到错误的结果.

my question is why i'm getting wrong results using a iterator variable in a lambda expression.

好吧,我遵循了SWeko的回答

Well i've followed SWeko's answer here. but it did not worked for me Here is my pseudo-code:

List<string> list = new List<string>(3);
// where list.Count=3
for (int i=0;i<list.Count;i++){
    int yy=i;
    AFunctionWithLambda(() => Console.WriteLine (list[yy]));
}

但是控制台只写

list[3]

3次,好像"yy"可能唯一的值是"i"的最后一个值 之所以奏效,是因为在声明"yy"变量之前,控制台返回了"i = 1",但这并不是真的,我不知道自己在想什么.

three times, as if the only value which "yy" could be is the last value of "i" It seemed to work because before declaring the "yy" variable, the Console returned "i=1" but it doesn't really, i don't know what i am mising.

感谢您的咨询!

推荐答案

很难从您的示例中看出来,因为它看起来结构完美并且可以正确捕获.这是我的扩展版本,可以正常工作:

It is hard to tell from your example, because it seems to be perfectly formed and correctly capturing. Here is my expanded version, and it works fine:

    public void Main()
    {
        List<string> list = new List<string>(3)
        { "a", "b", "c"};
        for (int i = 0; i < list.Count; i++)
        {
            int yy = i;
            AFunctionWithLambda(() => Console.WriteLine(list[yy]));
        }

        Thread.Sleep(1000);
        Console.WriteLine("all done, probably");
        Console.ReadLine();
    }

    private void AFunctionWithLambda(Action action)
    {  // runs it asynchronously, for giggles
        ThreadPool.QueueUserWorkItem(o => {
            Thread.Sleep(500); // delay, to let the loop finish
            action();
        });
    }

如果将其更改为:

        for (int i = 0; i < list.Count; i++)
        {
            AFunctionWithLambda(() => Console.WriteLine(list[i]));
        }

然后以单独描述的方式失败.

then it fails in the way described separately.

我们需要一个更好的例子; p

We will need a better example ;p

这篇关于C#-For循环和Lambda表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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