C# 在闭包中避免转义值

C# 在闭包中避免转义值,c#,closures,lazy-evaluation,linq-expressions,C#,Closures,Lazy Evaluation,Linq Expressions,假设我有以下代码: for(int i=0;i<10;i++) { //"i" is captured in the closure passed to LazyCreate MyApi.AddLazyCreate(() => new foo(/*other params*/ i)); } for(int i=0;i新foo(/*其他参数*/i)); } 这将导致意外行为,因为对于所有添加的闭包,“i”将为10 有没有安全的方法来避免这种情况? e、 g.如果我

假设我有以下代码:

for(int i=0;i<10;i++)
{
    //"i" is captured in the closure passed to LazyCreate
    MyApi.AddLazyCreate(() => new foo(/*other params*/ i)); 
}
for(int i=0;i新foo(/*其他参数*/i));
}
这将导致意外行为,因为对于所有添加的闭包,“i”将为10

有没有安全的方法来避免这种情况? e、 g.如果我使用
表达式设计api
如果每个“AddLazyCreate”检查传递的表达式并存储这些值的副本,那么应该可以实现预期的行为,对吗? 也就是说,我必须从表达式中编译每个参数,并获取参数的时间值,然后使用已计算的参数重新创建新表达式。 (表达式将始终是“新”表达式)

还是我遗漏了一些基本的东西? 在这些情况下,我还会有奇怪的行为吗?

你可以这样做:

for(int i=0; i<10; i++)
{
    int number = i;
    MyApi.AddLazyCreate(() => new foo(/*other params*/ number)); 
}
for(int i=0;i新foo(/*其他参数*/number));
}

这将导致它在循环的每次迭代中捕获不同的数字。

根据Eric的说法,这将在C#5@Maarten中“固定”,仅在foreach循环中。For循环仍然捕获最后一个结果。@TylerD87我站着更正:-)天哪,我怎么会错过这个!?,这种行为是否与早期版本的.NET有所不同??,我很确定唯一的方法是在它自己的函数中创建闭包,关闭函数args@RogerAlsing不,自从lambdas被引入后,这就起作用了。