将数组添加到列表将覆盖以前的元素 [英] Adding array to list overwrites previous elements

查看:219
本文介绍了将数组添加到列表将覆盖以前的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图通过遍历所有可能的颜色组合并将每个值添加到list来创建一个简单的颜色渐变位图.每个单独的RGB值都作为int数组存储在主list中.

I am trying to create a simple color gradient bitmap by iterating through all possible color combinations and adding each value to a list. Each individual RGB value is stored as an int array in the main list.

当我尝试将数组add放置到我的list时,对我来说出现了问题.它会覆盖list中的所有先前条目,最后我得到一个充满颜色数组的列表,所有这些数组都填充了值255.我知道,比这种笨拙的方法,必须存在一种更好的创建色谱位图的方法. ,但我对它为什么如此表现很感兴趣.

Problems occur for me when I am trying to add the array to my list. It overwrites all previous entries in the list, at last I end up with a list full of color arrays, all filled with the values 255. I know there must exist a better way to create a color spectrum bitmap than this rather clunky way, but I am very interested in why it behaves like this.

int[] temp = new int[3];
for (int r = 0; r < 256; r++)
{
    for (int g = 0; g < 256; g++)
    {
        for (int b = 0; b < 256; b++)
        {
            temp[0] = r;
            temp[1] = g;
            temp[2] = b;
            colors.Add(temp);
        }
    }
}

推荐答案

您的问题是temp是一个数组,而数组是引用类型.进行更改时,它会反映在以前添加的颜色值中.

You problem is that temp is an array and arrays are reference type. When you make change in it, it gets reflected in previously added values in colors.

您需要做

for (int r = 0; r < 256; r++)
{
    for (int g = 0; g < 256; g++)
    {
        for (int b = 0; b < 256; b++)
        {
            int[] temp = new int[3];
            temp[0] = r;
            temp[1] = g;
            temp[2] = b;
            colors.Add(temp);
        }
    }
}

这样,每个temp都将是一个新实例,并且colors的所有值都将不同.

This way every temp will be a fresh instance and all values of colors will be different.

这篇关于将数组添加到列表将覆盖以前的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆