Home >Backend Development >C++ >Capturing Copies or References in C# Lambdas: When Should You Choose Which?
When defining lambda expressions in C#, it is crucial to understand how they interact with external variables. By default, lambda expressions tend to capture references to external variables. However, in some cases it is crucial to force them to copy these variables.
Consider the following example, which is designed to print out a sequence of numbers using a Lambda expression and a loop:
<code class="language-csharp">class Program { delegate void Action(); static void Main(string[] args) { List<Action> actions = new List<Action>(); for (int i = 0; i < 10; i++) actions.Add(() => Console.WriteLine(i)); foreach (Action a in actions) a(); } }</code>
However, the above code snippet prints "10" repeatedly, indicating that the Lambda expression captures a reference to the shared variable i. Even if the value of i changes during the loop, the lambda expression always prints the final value of i, which is 10.
To force the lambda expression to capture a copy of the variable rather than a reference, one workaround is to create a local copy of the variable inside the loop:
<code class="language-csharp">for (int i = 0; i < 10; i++) { int copy = i; // 创建局部副本 actions.Add(() => Console.WriteLine(copy)); }</code>
By copying the value of i to a new variable copy, the Lambda expression effectively captures the value of i at a specific time and scope. This ensures that the lambda expression prints the correct number on each iteration of the loop.
Understanding this behavior is crucial for using lambda expressions in C#. It allows developers to control how lambda expressions interact with shared variables and ensures that programs run as expected.
The above is the detailed content of Capturing Copies or References in C# Lambdas: When Should You Choose Which?. For more information, please follow other related articles on the PHP Chinese website!