我有两个列表。当我将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));
当您分配List<T>
时,您将句柄复制到内存中的实际列表,这意味着两个变量都引用了相同的列表实例。
为了避免这种情况,您需要克隆列表本身。在这种情况下,这可能意味着需要做两件事——首先,找到克隆TrialBalance
的方法,然后也克隆列表:
// This assumes a TrialBalance.Clone() method which returns a new TrialBalance copy
this.PrevTBal = this.TBal.Select(tb => tb.Clone()).ToList();
更换
if (this.PrevTBal == null)
{
this.PrevTBal = this.TBal;
}
发件人:
if (this.PrevTBal == null)
{
this.PrevTBal = this.TBal.ToList();
}
通过这种方式,你实际上是在创建它的副本,而不仅仅是引用它