先看通常情况,非using语句中
在 C# 中,for 循环中的闭包通常会导致变量捕获的问题,因为匿名方法(或 lambda 表达式)在其创建时捕获了循环变量的引用,导致在后续的迭代中,它们引用的是已经被修改的变量。为了解决这个问题,你可以在循环体内声明一个临时变量,将循环变量的值赋给这个临时变量,然后在闭包中使用这个临时变量。
using System;
class Program
{
static void Main()
{
Action[] actions = new Action[3];
for (int i = 0; i < 3; i++)
{
int temp = i; // 创建临时变量并赋值
actions[i] = () => Console.WriteLine(temp);
}
foreach (var action in actions)
{
action();
}
}
}
在using语句中
在 using 语句下使用 for 循环时,同样需要注意避免闭包捕获问题。在 using 语句中,变量在离开 using 块时会被销毁,这可能导致闭包引用无效的变量。以下是一个示例,演示如何在 using 语句中使用 for 循环和闭包:
using System;
class Program
{
static void Main()
{
Action[] actions = new Action[3];
for (int i = 0; i < 3; i++)
{
int temp = i; // 创建临时变量并赋值
using (var disposable = new SampleDisposable())
{
actions[i] = () => Console.WriteLine($"Value: {temp}, Disposable: {disposable.Value}");
}
}
foreach (var action in actions)
{
action();
}
}
}
class SampleDisposable : IDisposable
{
public int Value { get; private set; }
public SampleDisposable()
{
Value = new Random().Next(100); // 模拟一些处理
}
public void Dispose()
{
Console.WriteLine($"Disposed: {Value}");
}
}
摸鱼老废物 你可以测试一下