当在某一行添加和Element时,List的C#计数会跳跃

  • 本文关键字:List 跳跃 Element 添加 一行 c#
  • 更新时间 :
  • 英文 :


我正在尝试使用实现邻接列表

List<List<int>>

但每次我在某个索引中添加新元素时,整个内部列表都会计数跳跃例如:

List<List<int>> neighbours = new List<List<int>>();
List<int> emptyList= new List<int>();
for (int i = 0; i < 5; i++) {
neighbours.Add(emptyList); 
neighbours[i].Add(0);
}

此时一切正常,list[anyIndex].count=1;但是当我做的时候

neighbours[3].add(1);

所有list[anyIndex].count跳到6知道发生了什么吗?

所有列表实际上都是一个相同的列表,因为添加了emptyList

相反,您需要创建new:

neighbours.add(new List<int>()); 

如果你想使用像emptyList这样可读的东西,你可以创建一个本地函数(C#7(:

List<int> emptyList() => new List<int>();
// ...
neighbours.Add(emptyList()); // creates always a new now

你可以试试这个:

List<List<int>> neighbours = new List<List<int>>();
for(int i=0 ; i < 5 ; i++){
neighbours.Add(new List<int>()); 
neighbours[i].Add(0);
}
for(int i=0 ; i < 5 ; i++){
Console.WriteLine(neighbours[i][0]);
}

最新更新