c# - 分配给 List 到另一个 List 之前的列表会自动改变

标签 c#

我有两个列表。当我将 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/

相关文章:

c# - 禁用 Topshelf 控制台输出

c# - 如何克隆 Collection<T>?

c# - 分组为元素字典

c# - 保存位图时不保留 Alpha 值

c# - 冗余控制流跳转语句

c# - 在 Realm 中使用特定于项目的 ViewModel 的最佳方式是什么?

c# - 磁盘上连续的内存映射文件

c# - 包含数字和字母的orderby()

c# - 代码找不到类

c# - 如何使用 DisplayName 检索属性名称?