foreach用起来比for更方便,但是foreach隐藏的操作,可能带来更多未知的BUG,今天就遇到一个问题.编程环境VS2010

//使用foreach遍历,其中未改变item的值,但是使用了匿名委托 item的值始终为rels.za.Asm的最后一位.百思不得其解,后改为for
           foreach (var item in rels.za.Asm.Count)
{
var item = rels.za.Asm[i];
item.pone.Extend.Addonly("string-性格", RandCells(), data => {
List<string> sary = (List<string>)data.value; string sc = "{0}是一个{1}的人。";
string sd = MES.Format(sc, item.pone.Name.ToString(), RandCellsms(sary));
return sd;
}); item.pone.Extend.Addonly("Appearance-长相", new WorldOne.People.Appearance(), data =>
{
WorldOne.People.Appearance aone = (WorldOne.People.Appearance)data.value;
return aone.ms(item.pone);
}); item.pone.Extend.Addonly("string-爱好", likes(item.pone), data =>
{
List<string> sary = (List<string>)data.value;
string scc = "{0}的爱好是{1}。";
string sdd = MES.Format(scc, item.pone.Name.ToString(), RandCellsms(sary));
return sdd;
});
}
           for (int i = ; i < rels.za.Asm.Count ; i++)  //使用for之后,数据读取正常
{
var item = rels.za.Asm[i];
item.pone.Extend.Addonly("string-性格", RandCells(), data => {
List<string> sary = (List<string>)data.value; string sc = "{0}是一个{1}的人。";
string sd = MES.Format(sc, item.pone.Name.ToString(), RandCellsms(sary));
return sd;
}); ..........

所以不管这个是不是foreach的BUG,都是使用foreach造成的问题,所以以后使用foreach要尽量避免一些非常规的操作.

05-19 19:40