您的位置:首页 > 编程语言 > C#

c# 用Dictionary.add 为什么将已添加元素内容改变了

2014-07-08 20:38 309 查看
此段代码实现将灰度值映射为伪彩值:

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的时候并不是单纯的内容复制,而是地址复制。


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c# 容器