[英]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. 出于某种原因,我希望Queue [2]包含元素,而所有其他列表(例如,Queue [0])的计数应为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. 问题是,据我所知,重复只重复引用同一个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: 如果我以这种方式使用fucntion,我会看到正确的结果:
Queue = InitList<List<object[]>>(3).ToList();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.