Arraylist.add()覆盖了由c#中的循环构建的Arraylist中的所有值

时间:2014-06-24 05:15:29

标签: c# arraylist

Arraylist.add()正在覆盖由c#中的循环构建的Arraylist中的所有先前值。代码是:

public ArrayList MakeList(int size,  int iterations)
{
    ArrayList myList = new ArrayList(iterations);

    for (int run = 0; run < iterations; run++)
    {
        byte[] _byteArray = new byte[size];
        bool success = false;
        while (!success)
        {
            //Some Operations 
            if(condition)
               success = true;
           else 
              continue;
            if(success)
              break;

        }
        myList .Add(_byteArray );
    }

    return myList;
}

上面的循环总是用最新的字节数组覆盖List中的值。请帮我解决这个问题。

1 个答案:

答案 0 :(得分:0)

Karthick最初认为这是一个深拷贝或浅拷贝的问题,但只要你在for循环中初始化字节数组就应该完美。我尝试在我的结尾处使用示例代码,当函数MakeList即将返回时,它可以正常工作。 myList指向的三个字节数组包含00,01,11,因为我已插入它们,并且没有按照您的建议进行覆盖。我已经硬编码了一些参数来快速输出:

public class Program
    {
        public static void Main(string[] args)
        {
            var col = new ColTest();
            col.MakeList();
         }        
}

public class ColTest
    {
        public ArrayList MakeList()
        {
            var capacity = 3;
            ArrayList myList = new ArrayList(capacity);
            int size = 2;
            for (int run = 0; run < capacity; run++)
            {
                byte[] _byteArray = new byte[size];

                if (run == 0)
                {
                    _byteArray[0] = 0;
                    _byteArray[1] = 0;
                }
                else if (run == 1)
                {
                    _byteArray[0] = 0;
                    _byteArray[1] = 1;
                }
                else if (run == 2)
                {
                    _byteArray[0] = 1;
                    _byteArray[1] = 1;
                }

                myList.Add(_byteArray);
            }

            return myList;
        }
    }

希望这有帮助!