Foreach中的C#Action
Foreach中的C#Action,c#,delegates,foreach,action,C#,Delegates,Foreach,Action,fMethod是一种操作 但是当调用fMethod时,参数始终是\u的最后一个条目 如何解决这个问题 foreach(Fruit f in _Fruits) { field.Add(new Element(f.ToString(),delegate{fMethod(f);})); } 在创建委托的调用中使用modified子句是一个众所周知的问题。添加临时变量应能解决此问题: foreach(Fruit f in _Fruits) { Fruit tmp = f; fie
fMethod
是一种操作
但是当调用fMethod
时,参数始终是\u的最后一个条目
如何解决这个问题
foreach(Fruit f in _Fruits)
{
field.Add(new Element(f.ToString(),delegate{fMethod(f);}));
}
在创建委托的调用中使用modified子句是一个众所周知的问题。添加临时变量应能解决此问题:
foreach(Fruit f in _Fruits)
{
Fruit tmp = f;
field.Add(new Element(f.ToString(),delegate{fMethod(tmp);}));
}
这个问题在C#5()中已修复。尝试使用临时变量
foreach(Fruit f in _Fruits)
{
var temp = f;
field.Add(new Element(temp.ToString(),delegate{fMethod(temp);}));
}
C#5.0中修复了此问题的可能副本:@DasKrümelmonster很高兴知道,非常感谢!