.net 下对于List的使用心得总结
2014-04-21 16:26
239 查看
在编写程序的时候,难免会用到List<T>泛型,近几天出现了在链表的时候出现了点小问题,我的本意是对一个List<List<int[,]>> list 做具体的操作,处理里面的int[,] 数据,刚开始的时候就是最基本的算法,将一个int[,] 构造完成后插入一个List<int[,]> ,当这个一串数据构造完成后在插入到整个链表中就可以了。具体代码如下:
但是出问题了:
row.clear()函数执行了之后,resultList里面刚刚添加的元素立马也被删除了,于是想到了把row放在循环里面,如下所示:
这样,虽然能够添加到链表里面,但是,还是出了问题,那就是添加的元素都是一样的,调试发现,每次添加新的,链表里面已经添加进去的元素也一起变成了最新的,最后一个完成后,整个链表就是最后一个的完全重复,真乃咄咄怪事。
于是继续分析:是因为每次添加的时候,使用的是同一个temp,(但是我已经new 一个新的了,不知道为什么还会这个样子),想到了使用它的副本,讲算法改成了如下:
仅仅改了一句,大功告成!!
至于之前那两个,我记得以前做的时候差不多都是这么写的啊,不知道为嘛就不行了,至于引用,传值云云的,如有大神偶尔路过,还望不理赐教。
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; }
仅仅改了一句,大功告成!!
至于之前那两个,我记得以前做的时候差不多都是这么写的啊,不知道为嘛就不行了,至于引用,传值云云的,如有大神偶尔路过,还望不理赐教。
相关文章推荐
- 淘宝接口 TopAPi
- SCWS中文分词,向xdb词库添加新词
- android 安装APP时,出现apk waiting for device这种状况!
- android照片墙的实现
- python网络编程中套接字的使用
- SQL Server Reporting Services – Timeout Settings
- Java ClassLoader深入讲解
- nodejs简介
- 解决乱码问题总结
- ubuntu svn服务器
- ---------------------http://www.cnblogs.com/jisheng/archive/2011/12/16/2290348.html
- FragmentDialog::Can not perform this action after onSaveInstanceState
- 数据存储模型
- LINK : fatal error LNK1123: 转换到 COFF 期间失败: 文件无效或损坏
- form插件ajaxForm和ajaxSubmit方法传递对象参数说明
- IOS应用之间调用
- 敏捷遇上UML(2014.4.19 广州站)- 活动报道
- ------------------Android中对GridView, ListView等滚动控件的Touch事件onInterceptTouchEvent,onTouchEvent了解
- ORACLE数据库测试数据插入速度
- Troubleshooting Timeout errors in Reporting Services