2013-12-20 49 views
2

我有两个列表。当我分配List1List2和我更新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; 
} 

回答

3

你只分配的参考,而不是建立在清单或列表中的项目的副本。

您应该创建一个新列表并添加所有项目。

this.PrevTBal = new List<TrialBalance>(this.TBal.Select(b => clone(b)); 
+0

有没有克隆()? – SHINHAN

+0

@SHINHAN'clone'是你需要做一个'TrialBalance'的副本。 –

+0

我很困惑如何克隆我的TrialBalance? – SHINHAN

3

当您将List<T>,你复制句柄在内​​存中的实际列表,这意味着相同的列表实例是由两个变量引用。

为了避免这种情况,您需要克隆列表本身。在这种情况下,需要有可能的手段做两两件事 - 第一,做一个方式克隆TrialBalance,然后克隆列表太:

// This assumes a TrialBalance.Clone() method which returns a new TrialBalance copy 
this.PrevTBal = this.TBal.Select(tb => tb.Clone()).ToList(); 
+0

这是一个非常受欢迎的面试问题,请查看将数据存储在堆栈或堆之间的区别。一旦你理解了这一点,你就不会再遇到这种问题了。http://www.c-sharpcorner.com/UploadFile/rmcochran/csharp_memory01122006130034PM/csharp_memory.aspx – Joshy

0

更换

if (this.PrevTBal == null) 
    { 
     this.PrevTBal = this.TBal; 
    } 

由:

if (this.PrevTBal == null) 
     { 
      this.PrevTBal = this.TBal.ToList(); 
     } 

这种方式你实际上是创建它的副本,而不是仅仅引用它。

+0

这将创建一个新的列表,但列表中的基本元素('TrialBalance')是相同的,所以改变第一个列表的第一个元素也会改变第二个列表中的第一个元素。这就是为什么其他解决方案也在克隆列表中的所有元素。 –

相关问题