为什么一个列表中的更改会影响其他列表? [英] Why change in one list affect other list?
问题描述
我有两个列表集合.
List<list<int>> FS = new List<List<int>>();List<List<int> V= new List<List<int>>()
我在FS
现在我的FS
外观
FS={{1},{2},{3}}
然后我将FS
的值分配给V
V = FS
现在我要遍历每对
Then i assigned valus of FS
to V
V = FS
Now i want to go through each pair
//Performing some Logic
for (int i = 0; i < FS.Count-1; i++)
{
for (int k = i + 1; k < FS.Count; k++)
{
List<int> temp = new List<int>();
temp.AddRange(FS[i]);
temp.AddRange(FS[k]);
VF.Add(IP_CFFM(temp));
V.Add(temp);
if (IP_CFFM(temp) > IP_CFFM(FS[i]) && IP_CFFM(temp) > IP_CFFM(FS[k]))
{
FS[i].AddRange(FS[k]);
FS.Remove(FS[k]);
}
}
}
在执行if(condition)
V
之前看起来像V = {{1},{2},{3},{1,2}}
但是在执行了FS[i].AddRange(FS[k]);
行之后,列表V发生了变化,看起来像{{1,2},{2},{3},{1,2}}
在if(condition)
内一样,我没有在V
上进行任何操作或执行任何操作.那为什么会发生呢?
Before executing if(condition)
V
will Look Like V = {{1},{2},{3},{1,2}}
But after executing the line FS[i].AddRange(FS[k]);
List V is changed and it look like {{1,2},{2},{3},{1,2}}
Within the if(condition)
, i am not manipulation or not performing anything on V
. Then why it happens?
推荐答案
List<T>
是一个类,因此是参考.
List<T>
is a class, so it is reference.
V = FS
实际上是指两个都指向相同的位置/地址空间.
V = FS
actually mean both pointing to same location/address space.
这意味着您对它所做的任何事情都会反映在另一个方面.只是您的List
This means that anything you do to it will be reflected in the other. It is just that two different names for your List
这篇关于为什么一个列表中的更改会影响其他列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!