我有两个列表。当我将 List1
分配给 List2
并更新 List1
时,List2
也会自动更新。 List2
不应更新。为什么会这样?
这是我的代码:
public List<TrialBalance> TBal { get; set; }
public List<TrialBalance> PrevTBal { get; private set; }
if (this.PrevTBal == null)
{
this.PrevTBal = this.TBal;
}
for (int x = 0; x < this.TBal.Count; x++)
{
this.TBal[x].Balance = this.TBal[x].Balance + adjustments;
}
最佳答案
您只是分配引用,而不是创建列表或列表中项目的副本。
您应该创建一个新列表并将所有项目添加到其中。
this.PrevTBal = new List<TrialBalance>(this.TBal.Select(b => clone(b));
关于c# - 分配给 List 到另一个 List 之前的列表会自动改变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20694397/