In C#, Lambda expressions can capture variables in the enclosing scope. When a Lambda captures a reference to a variable, any changes to that variable will be reflected in the Lambda. This can lead to unexpected behavior, as shown in the following code snippet:
<code class="language-C#">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>
When you run this code, it prints the number 10 ten times. This is because the Lambda function captures a reference to the variable i
and when i
is incremented in the for loop, the Lambda function still sees the updated value.
To capture a copy of a variable instead of a reference, you can use the following syntax:
<code class="language-C#">[=] () => { ... } // 捕获副本</code>
In this example, the Lambda function will capture a copy of the variable i
and any changes to i
in the enclosing scope will not be reflected in the Lambda function.
Here is a modified example demonstrating how to capture a copy:
<code class="language-C#">for (int i = 0; i < 10; i++) { int copy = i; // 创建一个局部副本 actions.Add(() => Console.WriteLine(copy)); }</code>
In this case, the Lambda function will print the value of copy
, which is a copy of the value of i
when the Lambda function was created.
By understanding the difference between capturing a reference and capturing a copy, you can avoid unexpected behavior in your Lambda functions.
The above is the detailed content of Reference vs. Copy in C# Lambda Capture: When Do I Get Unexpected Behavior?. For more information, please follow other related articles on the PHP Chinese website!