c# 用Dictionary.add 为什么将已添加元素内容改变了
2014-07-08 20:38
309 查看
此段代码实现将灰度值映射为伪彩值:
public void InitializeColorTemplate()
{
为什么此段代码 在调用colorTemplate.Add时,将已经添加的元素内容改变了呢,因为tempColor对象创建的位置有问题,应该将byte[] tempColor = new byte[3];这句话放在循环里面。对于List等容器也是一样。
因为在调用Add的时候并不是单纯的内容复制,而是地址复制。
public void InitializeColorTemplate()
{
byte[] tempColor = new byte[3]; for (int i = 0; i <= 255; i++) { if (i == 0) { tempColor[0] = 0; tempColor[1] = 0; tempColor[2] = 0; } if (i > 0 && i < 51) { tempColor[0] = 255; tempColor[1] = 255; tempColor[2] = 255; } else if (i >= 51 && i < 102) { tempColor[0] = 0; tempColor[1] = 0; tempColor[2] = 255; } else if (i >= 102 && i < 153) { tempColor[0] = 0; tempColor[1] = 255; tempColor[2] = 0; } else if (i >= 153 && i < 204) { tempColor[0] = 255; tempColor[1] = 255; tempColor[2] = 0; } else if (i >= 204 && i <= 255) { tempColor[0] = 255; tempColor[1] = 0; tempColor[2] = 0; } colorTemplate.Add((byte)i, tempColor); } }
为什么此段代码 在调用colorTemplate.Add时,将已经添加的元素内容改变了呢,因为tempColor对象创建的位置有问题,应该将byte[] tempColor = new byte[3];这句话放在循环里面。对于List等容器也是一样。
因为在调用Add的时候并不是单纯的内容复制,而是地址复制。
相关文章推荐
- JavaScript HTML DOM---遗漏知识再整理(向html添加/删除元素,改变内容和css)
- C# XML 给一个元素添加带有内容的子元素
- C# WINFORM中的combobox.items.add实现像web开发那样,添加显示内容text和实际value值
- C#.NET底层 List 集合循环添加对象(如:list.add(model)),为什么会出现整个list集合都是一样的数据?
- iOS/Xcode异常:对象数组NSMutableArray添加元素-addObject,但count方法仍然返回0?
- 用C#根据内容创建xml元素节点名不乎时规则时的一种很2的写法。
- C#显示(读取)XML元素内容的简单例子
- c#中List <int[]>集合添加和查找元素
- C#提取Word中的内容并添加到另一人word中
- 为什么java中迭代过程中不可以不可以添加或删除元素
- C#程序模拟键盘输入向记事本内添加内容
- 带有命名空间的xml添加属性和元素(c#.NET)
- C# List<> add函数总是覆盖List中原有元素的解决办法
- 为什么我改变了Richtextbox的text内容后,滚动条就变disable了,只能用鼠标滚轮。。。 (附解决办法)
- C# List 添加元素的问题(为什么我的元素都变一样了)
- 在后台得到前台元素,给元素改变属性值或添加属性
- C# Dictionary.Add(key,"123") 与 Dictionary[key]="123"的区别
- c#中List <int[]>集合添加和查找元素
- c#中List <int[]>集合添加和查找元素
- c#中向listbox添加大量元素的快速方法