您的位置:首页 > 其它

.net 下对于List的使用心得总结

2014-04-21 16:26 239 查看
在编写程序的时候,难免会用到List<T>泛型,近几天出现了在链表的时候出现了点小问题,我的本意是对一个List<List<int[,]>> list 做具体的操作,处理里面的int[,] 数据,刚开始的时候就是最基本的算法,将一个int[,] 构造完成后插入一个List<int[,]> ,当这个一串数据构造完成后在插入到整个链表中就可以了。具体代码如下:

public List<List<int[,]>> dealList(List<List<int[,]>> orinalList) {
List<List<int[,]>> resultList = new List<List<int[,]>>();
List<int[,]> row = new List<int[,]>();
int[,]  temp= new int[8, 8];
foreach (List<int[,]> list_temp in resultList) {
foreach (int[,] int_temp in list_temp) {
//do some thing for temp
row.Add(temp);
}
resultList.Add(row);
row.Clear();
}
return resultList;
}


但是出问题了:

row.clear()函数执行了之后,resultList里面刚刚添加的元素立马也被删除了,于是想到了把row放在循环里面,如下所示:

public List<List<int[,]>> dealList(List<List<int[,]>> orinalList)
{
List<List<int[,]>> resultList = new List<List<int[,]>>();
foreach (List<int[,]> list_temp in resultList)
{
List<int[,]> row = new List<int[,]>();
foreach (int[,] int_temp in list_temp)
{
int[,] temp = new int[8, 8];
//do some thing for temp

row.Add(temp);
}
resultList.Add(row);
row.Clear();
}
return resultList;
}


这样,虽然能够添加到链表里面,但是,还是出了问题,那就是添加的元素都是一样的,调试发现,每次添加新的,链表里面已经添加进去的元素也一起变成了最新的,最后一个完成后,整个链表就是最后一个的完全重复,真乃咄咄怪事。

于是继续分析:是因为每次添加的时候,使用的是同一个temp,(但是我已经new 一个新的了,不知道为什么还会这个样子),想到了使用它的副本,讲算法改成了如下:

public List<List<int[,]>> dealList(List<List<int[,]>> orinalList)
{
List<List<int[,]>> resultList = new List<List<int[,]>>();
foreach (List<int[,]> list_temp in resultList)
{
List<int[,]> row = new List<int[,]>();
foreach (int[,] int_temp in list_temp)
{
int[,] temp = new int[8, 8];
//do some thing for temp

row.Add((int[,])temp.Clone());
}
resultList.Add(row);
row.Clear();
}
return resultList;
}


仅仅改了一句,大功告成!!

至于之前那两个,我记得以前做的时候差不多都是这么写的啊,不知道为嘛就不行了,至于引用,传值云云的,如有大神偶尔路过,还望不理赐教。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: