一个列表上的AddLast()添加到列表C#数组中的所有列表



我基本上有以下代码:

LinkedList<int>[] listOfNumbers = new LinkedList<int>[6];
int[] someNumbers = new int[6];
for(int index = 0; index < 6; index++)
{
  listOfNumbers[index] = new LinkedList<int>();
}
someNumnbers[0] = 0;
someNumnbers[1] = 1;
someNumnbers[2] = 2;
someNumnbers[3] = 3;
someNumnbers[4] = 4;
someNumnbers[5] = 5;
for(int index = 0; index < 6; index++)
{
  listOfNumbers[index].AddLast(someNumbers[index]);
}

在最后一个循环的第一次传递之后,我期望Visual Studio中的对象监视工具提供以下报告:

listOfNumbers[0] has 1 element with value 0
listOfNumbers[1] has no elements
listOfNumbers[2] has no elements
listOfNumbers[3] has no elements
listOfNumbers[4] has no elements
listOfNumbers[5] has no elements

但我却奇怪地发现:

listOfNumbers[0] has 1 element with value 0
listOfNumbers[1] has 1 element with value 0
listOfNumbers[2] has 1 element with value 0
listOfNumbers[3] has 1 element with value 0
listOfNumbers[4] has 1 element with value 0
listOfNumbers[5] has 1 element with value 0

当我运行最后一个循环直到它完成时,我得到以下内容:

listOfNumbers[0] has 6 element with values 0,1,2,3,4,5
listOfNumbers[1] has 6 element with values 0,1,2,3,4,5
listOfNumbers[2] has 6 element with values 0,1,2,3,4,5
listOfNumbers[3] has 6 element with values 0,1,2,3,4,5
listOfNumbers[4] has 6 element with values 0,1,2,3,4,5
listOfNumbers[5] has 6 element with values 0,1,2,3,4,5

与我期望得到的相比:

listOfNumbers[0] has 1 element with value 0
listOfNumbers[1] has 1 element with value 1
listOfNumbers[2] has 1 element with value 2
listOfNumbers[3] has 1 element with value 3
listOfNumbers[4] has 1 element with value 4
listOfNumbers[5] has 1 element with value 5

我的第一个猜测是我写了一些语法错误的东西,但我似乎不明白是什么。很明显,它似乎在每次传递时都将AddLast()应用于列表数组中的每个列表,但我不知道为什么。如有任何帮助,我们将不胜感激。

如果您在每个索引中都有相同的链表实例,则会发生这种情况,如果您实际正在初始化linkedlist数组,就像您所显示的那样,这应该不会有问题。相同的实例意味着u将链表实例化为一个变量,然后在每个数组索引中分配该链表,这本质上意味着,由于无论你在哪个对象中调用addlast方法,它们在内部都是相同的对象,因此它将反映在数组中的每个项中。

我认为您正在制作一个LinkedList数组,而您只想使用LinkedList。

尝试将其初始化为单个LinkedList,然后添加元素。

查看文档中提供的LinkedList<T>类的使用示例:http://msdn.microsoft.com/it-it/library/he2s3bh7(v=vs.110).aspx

您应该尝试使用两个for循环执行以下操作。外循环用于通过每个列表,内循环用于填充每个列表。

for(int i=0; i<6;i++)
{
for(int index = 0; index < 6; index++)
{
  listOfNumbers[i].AddLast(someNumbers[index]);
}
}

相关内容

  • 没有找到相关文章

最新更新