关闭捕捉变量修改原始以及 [英] Closure captured variable modifies the original as well

查看:92
本文介绍了关闭捕捉变量修改原始以及的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下简单的code:

I have the following simple code:

static void Main(string[] args)
{
    int j = 0;
    Func<int> f = () =>
    {
        for (int i = 0; i < 3; i++)
        {
            j += i;
        }
        return j;
    };

    int myStr = f();
    Console.WriteLine(myStr);
    Console.WriteLine(j);
    Console.Read();
}

从我读涉及关闭的时候,一个新的类型由编译器生成的,因此它可以存储所捕获的变量,并保持对它的引用。然而,当我运行下面的code,这两种印刷线显示3。我期待0和3,因为匿名方法由编译器生成的类都有其自己的变量。那么,为什么它还要修改以外的变量?

From what I read when closures are involved, a new type is created by the compiler so it can store the captured variable and maintain a reference to it. However, when I run the following code, both printed lines show 3. I was expecting 0 and 3, because the anonymous method has its own variable in the generated class by the compiler. So why does it also modify the outside variable?

推荐答案

外面的变量,并在封闭的变量是的相同的变量的。你的程序是等价于:

The outside variable and the variable in the closure are the same variable. Your program is equivalent to:

private class Closure
{
    public int j;
    public int Method()
    {
        for (int i = 0; i < 3; i++)
        {
            this.j += i;
        }
        return this.j;
    }
}
static void Main(string[] args)
{
    Closure closure = new Closure();
    closure.j = 0;
    Func<int> f = closure.Method;
    int myStr = f();
    Console.WriteLine(myStr);
    Console.WriteLine(closure.j);
    Console.Read();
}

现在是明确为什么你所观察到的结果呢?

Now is it clear why you get the observed result?

这篇关于关闭捕捉变量修改原始以及的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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