在C#中的循环中捕获的变量

发布于 2025-02-10 02:32:10 字数 436 浏览 4 评论 0 原文

我遇到了一个关于C#的有趣问题。我的代码如下。

List<Func<int>> actions = new List<Func<int>>();

int variable = 0;
while (variable < 5)
{
    actions.Add(() => variable * 2);
    ++ variable;
}

foreach (var act in actions)
{
    Console.WriteLine(act.Invoke());
}

我希望它输出0、2、4、6、8。但是,它实际上输出了五个10。

看来这是由于所有涉及一个捕获变量的动作所致。结果,当他们被调用时,它们都具有相同的输出。

有没有办法在此限制中工作以使每个动作实例都有自己的捕获变量?

I met an interesting issue about C#. I have code like below.

List<Func<int>> actions = new List<Func<int>>();

int variable = 0;
while (variable < 5)
{
    actions.Add(() => variable * 2);
    ++ variable;
}

foreach (var act in actions)
{
    Console.WriteLine(act.Invoke());
}

I expect it to output 0, 2, 4, 6, 8. However, it actually outputs five 10s.

It seems that it is due to all actions referring to one captured variable. As a result, when they get invoked, they all have same output.

Is there a way to work round this limit to have each action instance have its own captured variable?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(11

始于初秋 2025-02-17 02:32:10

是的 - 播放循环内部变量的副本:

while (variable < 5)
{
    int copy = variable;
    actions.Add(() => copy * 2);
    ++ variable;
}

您可以将其视为C#编译器每次击中变量声明时都会创建“新”本地变量一样。实际上,它将创建适当的新闭合对象,如果您参考多个范围中的变量,它会变得复杂(在实现方面),但它有效:)

请注意,此问题更常见的发生是使用 for foreach

for (int i=0; i < 10; i++) // Just one variable
foreach (string x in foo) // And again, despite how it reads out loud

有关此信息的更多详细信息,请参见C#3.0规格的7.14.4.4节,以及我的有关关闭的文章也有更多示例。

请注意,从C#5编译器及以后(即使指定较早版本的C#), foreach 的行为也更改了,因此您不再需要进行本地副本。请参阅答案有关更多详细信息。

Yes - take a copy of the variable inside the loop:

while (variable < 5)
{
    int copy = variable;
    actions.Add(() => copy * 2);
    ++ variable;
}

You can think of it as if the C# compiler creates a "new" local variable every time it hits the variable declaration. In fact it'll create appropriate new closure objects, and it gets complicated (in terms of implementation) if you refer to variables in multiple scopes, but it works :)

Note that a more common occurrence of this problem is using for or foreach:

for (int i=0; i < 10; i++) // Just one variable
foreach (string x in foo) // And again, despite how it reads out loud

See section 7.14.4.2 of the C# 3.0 spec for more details of this, and my article on closures has more examples too.

Note that as of the C# 5 compiler and beyond (even when specifying an earlier version of C#), the behavior of foreach changed so you no longer need to make local copy. See this answer for more details.

最偏执的依靠 2025-02-17 02:32:10

I believe what you are experiencing is something known as Closure http://en.wikipedia.org/wiki/Closure_(computer_science). Your lamba has a reference to a variable which is scoped outside the function itself. Your lamba is not interpreted until you invoke it and once it is it will get the value the variable has at execution time.

久随 2025-02-17 02:32:10

在幕后,编译器正在生成一个代表您方法呼叫的关闭的类。它使用循环的每个迭代使用闭合类的单个实例。该代码看起来像这样,这使您更容易查看为什么发生错误的原因:

void Main()
{
    List<Func<int>> actions = new List<Func<int>>();

    int variable = 0;

    var closure = new CompilerGeneratedClosure();

    Func<int> anonymousMethodAction = null;

    while (closure.variable < 5)
    {
        if(anonymousMethodAction == null)
            anonymousMethodAction = new Func<int>(closure.YourAnonymousMethod);

        //we're re-adding the same function 
        actions.Add(anonymousMethodAction);

        ++closure.variable;
    }

    foreach (var act in actions)
    {
        Console.WriteLine(act.Invoke());
    }
}

class CompilerGeneratedClosure
{
    public int variable;

    public int YourAnonymousMethod()
    {
        return this.variable * 2;
    }
}

这实际上不是您的示例中编译的代码,但是我已经检查了自己的代码,这看起来很像编译器实际生成的代码。

Behind the scenes, the compiler is generating a class that represents the closure for your method call. It uses that single instance of the closure class for each iteration of the loop. The code looks something like this, which makes it easier to see why the bug happens:

void Main()
{
    List<Func<int>> actions = new List<Func<int>>();

    int variable = 0;

    var closure = new CompilerGeneratedClosure();

    Func<int> anonymousMethodAction = null;

    while (closure.variable < 5)
    {
        if(anonymousMethodAction == null)
            anonymousMethodAction = new Func<int>(closure.YourAnonymousMethod);

        //we're re-adding the same function 
        actions.Add(anonymousMethodAction);

        ++closure.variable;
    }

    foreach (var act in actions)
    {
        Console.WriteLine(act.Invoke());
    }
}

class CompilerGeneratedClosure
{
    public int variable;

    public int YourAnonymousMethod()
    {
        return this.variable * 2;
    }
}

This isn't actually the compiled code from your sample, but I've examined my own code and this looks very much like what the compiler would actually generate.

李不 2025-02-17 02:32:10

这与循环无关。

触发此行为是因为您使用lambda表达式()=&gt;变量 * 2 其中外部范围变量实际上未在lambda的内部范围中定义。

Lambda表达式(在C#3+中以及C#2中的匿名方法)仍然创建实际方法。将变量传递给这些方法涉及一些困境(按值传递?逐个引用?c#通过参考将带来 - 但这打开了另一个问题,参考可以超过实际变量)。 C#要解决所有这些困境的工作是创建一个新的助手类(“闭合”),其字段与lambda表达式中使用的局部变量相对应,以及与实际lambda方法相对应的方法。代码中对变量的任何更改实际上都会翻译为更改该 clocreclass.variable

因此您的wier loop不断更新 collecleclass.variable.variable 直到它到达10,然后您进行循环执行操作,所有操作都在相同的 colleclaclass.variable 上进行操作。

为了获得预期的结果,您需要在循环变量与正在关闭的变量之间创建一个分离。您可以通过引入另一个变量,即:

List<Func<int>> actions = new List<Func<int>>();
int variable = 0;
while (variable < 5)
{
    var t = variable; // now t will be closured (i.e. replaced by a field in the new class)
    actions.Add(() => t * 2);
    ++variable; // changing variable won't affect the closured variable t
}
foreach (var act in actions)
{
    Console.WriteLine(act.Invoke());
}

您也可以将闭合移动到创建此分隔的方法:

List<Func<int>> actions = new List<Func<int>>();

int variable = 0;
while (variable < 5)
{
    actions.Add(Mult(variable));
    ++variable;
}

foreach (var act in actions)
{
    Console.WriteLine(act.Invoke());
}

您可以将元用作lambda表达式(隐式闭合)

static Func<int> Mult(int i)
{
    return () => i * 2;
}

或实际助手类别实现:

public class Helper
{
    public int _i;
    public Helper(int i)
    {
        _i = i;
    }
    public int Method()
    {
        return _i * 2;
    }
}

static Func<int> Mult(int i)
{
    Helper help = new Helper(i);
    return help.Method;
}

无论如何:在任何情况下:“封闭”不是与环路< / strong>有关的概念,而是与匿名方法 / lambda表达式使用本地范围示波器变量的概念 - 尽管对环的某些不典型的使用表明了闭合陷阱。

This has nothing to do with loops.

This behavior is triggered because you use a lambda expression () => variable * 2 where the outer scoped variable not actually defined in the lambda's inner scope.

Lambda expressions (in C#3+, as well as anonymous methods in C#2) still create actual methods. Passing variables to these methods involve some dilemmas (pass by value? pass by reference? C# goes with by reference - but this opens another problem where the reference can outlive the actual variable). What C# does to resolve all these dilemmas is to create a new helper class ("closure") with fields corresponding to the local variables used in the lambda expressions, and methods corresponding to the actual lambda methods. Any changes to variable in your code is actually translated to change in that ClosureClass.variable

So your while loop keeps updating the ClosureClass.variable until it reaches 10, then you for loops executes the actions, which all operate on the same ClosureClass.variable.

To get your expected result, you need to create a separation between the loop variable, and the variable that is being closured. You can do this by introducing another variable, i.e.:

List<Func<int>> actions = new List<Func<int>>();
int variable = 0;
while (variable < 5)
{
    var t = variable; // now t will be closured (i.e. replaced by a field in the new class)
    actions.Add(() => t * 2);
    ++variable; // changing variable won't affect the closured variable t
}
foreach (var act in actions)
{
    Console.WriteLine(act.Invoke());
}

You could also move the closure to another method to create this separation:

List<Func<int>> actions = new List<Func<int>>();

int variable = 0;
while (variable < 5)
{
    actions.Add(Mult(variable));
    ++variable;
}

foreach (var act in actions)
{
    Console.WriteLine(act.Invoke());
}

You can implement Mult as a lambda expression (implicit closure)

static Func<int> Mult(int i)
{
    return () => i * 2;
}

or with an actual helper class:

public class Helper
{
    public int _i;
    public Helper(int i)
    {
        _i = i;
    }
    public int Method()
    {
        return _i * 2;
    }
}

static Func<int> Mult(int i)
{
    Helper help = new Helper(i);
    return help.Method;
}

In any case, "Closures" are NOT a concept related to loops, but rather to anonymous methods / lambda expressions use of local scoped variables - although some incautious use of loops demonstrate closures traps.

苍暮颜 2025-02-17 02:32:10

这样做的方法是将所需的值存储在代理变量中,并捕获该变量。

IE

while( variable < 5 )
{
    int copy = variable;
    actions.Add( () => copy * 2 );
    ++variable;
}

The way around this is to store the value you need in a proxy variable, and have that variable get captured.

I.E.

while( variable < 5 )
{
    int copy = variable;
    actions.Add( () => copy * 2 );
    ++variable;
}
一页 2025-02-17 02:32:10

是的,您需要在循环中范围变量将其传递给lambda:

List<Func<int>> actions = new List<Func<int>>();

int variable = 0;
while (variable < 5)
{
    int variable1 = variable;
    actions.Add(() => variable1 * 2);
    ++variable;
}

foreach (var act in actions)
{
    Console.WriteLine(act.Invoke());
}

Console.ReadLine();

Yes you need to scope variable within the loop and pass it to the lambda that way:

List<Func<int>> actions = new List<Func<int>>();

int variable = 0;
while (variable < 5)
{
    int variable1 = variable;
    actions.Add(() => variable1 * 2);
    ++variable;
}

foreach (var act in actions)
{
    Console.WriteLine(act.Invoke());
}

Console.ReadLine();
吐个泡泡 2025-02-17 02:32:10

多线程(c#,。net 4.0

] :

是打印1,2,3,4,5的顺序。

for (int counter = 1; counter <= 5; counter++)
{
    new Thread (() => Console.Write (counter)).Start();
}

目的

代码

for (int counter = 1; counter <= 5; counter++)
{
    int localVar= counter;
    new Thread (() => Console.Write (localVar)).Start();
}

The same situation is happening in multi-threading (C#, .NET 4.0].

See the following code:

Purpose is to print 1,2,3,4,5 in order.

for (int counter = 1; counter <= 5; counter++)
{
    new Thread (() => Console.Write (counter)).Start();
}

The output is interesting! (It might be like 21334...)

The only solution is to use local variables.

for (int counter = 1; counter <= 5; counter++)
{
    int localVar= counter;
    new Thread (() => Console.Write (localVar)).Start();
}
旧情别恋 2025-02-17 02:32:10

正如其他人所说的那样,这与循环无关。这是c#中匿名功能正文中变量捕获机制的效果。
当您将lambda定义为示例时;

actions.Add(() => variable * 2);

编译器生成一个容器类,例如&lt;&gt; c__displayClass0_0 for lambda函数
()=&gt; ()=&gt;变量 * 2

在生成的类(容器)的内部,它生成一个名为 变量的字段 ,具有具有相同名称的捕获变量,而方法b__0()包含lambda的主体。

[CompilerGenerated]
private sealed class <>c__DisplayClass0_0
{
public int variable;

internal int <Main>b__0()
{
    return variable * 2;
}
}

而不是命名变量的局部变量,它成为容器类(&lt;&gt;&gt; c__displayClass0_0)的字段,

<>c__DisplayClass0_.variable = 0;
while (<>c__DisplayClass0_.variable < 5)
{
    list.Add(new Func<int>(<>c__DisplayClass0_.<Main>b__0));
    <>c__DisplayClass0_.variable++;
}

因此递增变量结果转向集装箱类别的字段,并且因为我们获得了一个容器类的实例,用于While循环的所有迭代,我们将获得相同的输出

。 i.sstatic.net/1ds8x.png“ alt =“在此处输入图像说明”>

您可以通过将循环体内的捕获变量重新分配到新的本地变量中,以防新的局部变量

while (variable < 5)
{
    var index = variable; // <= this line
    actions.Add(() => index * 2);
    ++ variable;
}

,此行为仍然有效使用.NET 8预览,我发现这种行为非常越来越大。

As others said It has nothing to do with loops.It is the effect of the variable capture mechanism in the body of anonymous functions in C#.
When you define lambda as your example ;

actions.Add(() => variable * 2);

Compiler generates a container class like <>c__DisplayClass0_0 for the lambda function
() => () => variable * 2.

Inside of the generated class(container) it generates a field named as variable, having a captured variable with the same name and the method b__0() containing the body of the lambda.

[CompilerGenerated]
private sealed class <>c__DisplayClass0_0
{
public int variable;

internal int <Main>b__0()
{
    return variable * 2;
}
}

And than local variable named variable, becomes a field of a container class(<>c__DisplayClass0_0)

<>c__DisplayClass0_.variable = 0;
while (<>c__DisplayClass0_.variable < 5)
{
    list.Add(new Func<int>(<>c__DisplayClass0_.<Main>b__0));
    <>c__DisplayClass0_.variable++;
}

So incrementing variable results in turn incrementing field of container class and because we get one instance of the container class for all iterations of the while loop,we get same output that is 10.

enter image description here

You can prevent by reassigning captured variable inside the body of the loop to a new local variable

while (variable < 5)
{
    var index = variable; // <= this line
    actions.Add(() => index * 2);
    ++ variable;
}

By the way,this behaviour still is valid with .Net 8 Preview and I find this behaviour is very buggy and deceptive.

oО清风挽发oО 2025-02-17 02:32:10
for (int n=0; n < 10; n++) //forloop syntax
foreach (string item in foo) foreach syntax
for (int n=0; n < 10; n++) //forloop syntax
foreach (string item in foo) foreach syntax
飘逸的'云 2025-02-17 02:32:10

它称为封闭问题,
只需使用复制变量即可完成。

List<Func<int>> actions = new List<Func<int>>();

int variable = 0;
while (variable < 5)
{
    int i = variable;
    actions.Add(() => i * 2);
    ++ variable;
}

foreach (var act in actions)
{
    Console.WriteLine(act.Invoke());
}

It is called the closure problem,
simply use a copy variable, and it's done.

List<Func<int>> actions = new List<Func<int>>();

int variable = 0;
while (variable < 5)
{
    int i = variable;
    actions.Add(() => i * 2);
    ++ variable;
}

foreach (var act in actions)
{
    Console.WriteLine(act.Invoke());
}
阳光下慵懒的猫 2025-02-17 02:32:10

由于这里没有人直接引用 ecma-334

语句的10.4.4.10

确定的分配检查以下表格:

for (for-initializer; for-condition; for-iterator) embedded-statement

就像写了语句一样:

{
    for-initializer;
    while (for-condition) {
        embedded-statement;
    LLoop: for-iterator;
    }
}

在规格中进一步,

12.16.6.3局部变量的实例化

当执行进入变量范围时,局部变量被认为是实例化的。

[示例:例如,当调用以下方法时,本地变量 x 是实例化并初始化了三次 - 每次迭代循环。

static void F() {
  for (int i = 0; i < 3; i++) {
    int x = i * 2 + 1;
    ...
  }
}

但是,将 x 的声明移动在循环外部导致 x 的单个实例化:

static void F() {
  int x;
  for (int i = 0; i < 3; i++) {
    x = i * 2 + 1;
    ...
  }
}

结束示例]

未被捕获时,无法确切观察到局部变量被实例化的频率 - 因为实例的寿命是不相交的,每个实例都可以简单地使用相同的存储位置。但是,当匿名函数捕获局部变量时,实例化的效果变得显而易见。

[示例:示例

using System;

delegate void D();

class Test{
  static D[] F() {
    D[] result = new D[3];
    for (int i = 0; i < 3; i++) {
      int x = i * 2 + 1;
      result[i] = () => { Console.WriteLine(x); };
    }
  return result;
  }
  static void Main() {
    foreach (D d in F()) d();
  }
}

产生输出:

1
3
5

但是,当 x 的声明在循环外移动时:

static D[] F() {
  D[] result = new D[3];
  int x;
  for (int i = 0; i < 3; i++) {
    x = i * 2 + 1;
    result[i] = () => { Console.WriteLine(x); };
  }
  return result;
}

输出为:

5
5
5

请注意,允许编译器(但不需要)将三个实例化到单个代表实例(§11.7.2)。

如果循环声明迭代变量,则该变量本身被认为是在循环之外声明的。
[示例:因此,如果更改了示例以捕获迭代变量本身:

static D[] F() {
  D[] result = new D[3];
  for (int i = 0; i < 3; i++) {
    result[i] = () => { Console.WriteLine(i); };
  }
  return result;
}

仅捕获迭代变量的一个实例,该实例产生输出:

3
3
3

结束示例]

,是的,我想应该提到的是,在C ++中没有发生此问题,因为您可以选择该变量是通过值或参考捕获的(请参阅: lambda捕获)。

Since no one here directly quoted ECMA-334:

10.4.4.10 For statements

Definite assignment checking for a for-statement of the form:

for (for-initializer; for-condition; for-iterator) embedded-statement

is done as if the statement were written:

{
    for-initializer;
    while (for-condition) {
        embedded-statement;
    LLoop: for-iterator;
    }
}

Further on in the spec,

12.16.6.3 Instantiation of local variables

A local variable is considered to be instantiated when execution enters the scope of the variable.

[Example: For example, when the following method is invoked, the local variable x is instantiated and initialized three times—once for each iteration of the loop.

static void F() {
  for (int i = 0; i < 3; i++) {
    int x = i * 2 + 1;
    ...
  }
}

However, moving the declaration of x outside the loop results in a single instantiation of x:

static void F() {
  int x;
  for (int i = 0; i < 3; i++) {
    x = i * 2 + 1;
    ...
  }
}

end example]

When not captured, there is no way to observe exactly how often a local variable is instantiated—because the lifetimes of the instantiations are disjoint, it is possible for each instantation to simply use the same storage location. However, when an anonymous function captures a local variable, the effects of instantiation become apparent.

[Example: The example

using System;

delegate void D();

class Test{
  static D[] F() {
    D[] result = new D[3];
    for (int i = 0; i < 3; i++) {
      int x = i * 2 + 1;
      result[i] = () => { Console.WriteLine(x); };
    }
  return result;
  }
  static void Main() {
    foreach (D d in F()) d();
  }
}

produces the output:

1
3
5

However, when the declaration of x is moved outside the loop:

static D[] F() {
  D[] result = new D[3];
  int x;
  for (int i = 0; i < 3; i++) {
    x = i * 2 + 1;
    result[i] = () => { Console.WriteLine(x); };
  }
  return result;
}

the output is:

5
5
5

Note that the compiler is permitted (but not required) to optimize the three instantiations into a single delegate instance (§11.7.2).

If a for-loop declares an iteration variable, that variable itself is considered to be declared outside of the loop.
[Example: Thus, if the example is changed to capture the iteration variable itself:

static D[] F() {
  D[] result = new D[3];
  for (int i = 0; i < 3; i++) {
    result[i] = () => { Console.WriteLine(i); };
  }
  return result;
}

only one instance of the iteration variable is captured, which produces the output:

3
3
3

end example]

Oh yea, I guess it should be mentioned that in C++ this problem doesn't occur because you can choose if the variable is captured by value or by reference (see: Lambda capture).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文