简体   繁体   中英

C# List<List<object[]>>() issue - Weird behavior

I've been trying to do the following:

public List<List<object[]>> Queue = new List<List<object[]>>();
Queue = InitList(MaxLayerCapability, new List<object[]>());

Having

public List<T> InitList<T>(int count, T initValue)
        {
            return Enumerable.Repeat(initValue, count).ToList();
        }

So here is where the issue resides:

Queue[2].Add(new object[] { "Draw", "Test" });

            for ( int i = 0; i < MaxLayerCapability; i++)
            {
                Console.WriteLine(i + ">" + Queue[i].Count);
                //Operate(Queue[i], i);
            }

For some reason, I want that Queue[2] to contains elements, and all other lists (for example, Queue[0]) should have a count of 0.

It is at some point pushing all the elements into Queue, any ideas?

Here's what I'm getting:

0>1
1>1
2>1
3>1
4>1
5>1

Thanks in advance.

The problem is, as i understand it, that Repeat just repeats reference to the same instance of List. I would refactor it this way:

public IEnumerable<T> InitList<T>(int count)  
{
  for (int i=0;i<count; i++)
  {
     yield return Activator.CreateInstance<T>();
  }            
}

I see correct results if i use fucntion this way:

Queue = InitList<List<object[]>>(3).ToList();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM