c# - 在 Windows 窗体 C# 中,更新 List<List<T>> 更新已输入的 List<T> 条目

标签 c# winforms list

我有一个名为粒子的对象,它有自己的属性(位置、速度等),并且在我的窗口窗体中创建了一个粒子列表。然后在代码中更新该粒子列表(即每个粒子的位置、速度等在每个迭代步骤中更新)。

我想做的是添加这个List<Particle>到另一个列表List<List<Particle>>每次迭代(单击按钮后),这样我现在就有了可以比较的单独粒子列表。

这就是我的代码的样子(UpdateEngine 是一个类,它在其初始化方法中创建粒子列表,然后使用其他方法更新其列表中粒子的值):

public partial class frmMain : Form
{
    private List<List<Particle>> listPlist;

    private UpdateEngine Engine;

    ...

    public frmMain()
    {
        InitializeComponent();

        listPlist = new List<List<Particle>>();

        Engine = new UpdateEngine();
    }

    ...

    //pressing this button iterates through a specified number of iterations
    private void btPrep_Click(object sender, EventArgs e)
    {            
        //create the particles and add the first list to the list of lists
        Engine.Initialize();
        listPlist.Add(Engine.ParticleList);

        //iterate through the list of particles in Engine and update their properties
        for(i = 0; i <= iterations; i++)
        {
            Engine.Update();
            listPlist.Add(Engine.ParticleList);
        }
    }
}

我看到发生的情况是,第一个列表是在迭代之前添加的。 for 循环中添加的第一个列表添加得很好。此后添加的每个列表都会更改 listPlist 中的所有列表,使其与当前列表相同。

运行代码时看到的示例:

初始化后:

  • listPlist(0) > 粒子(0) > 位置 = 0,0

第一次迭代后:

  • listPlist(0) > 粒子(0) > 位置 = 0,0
  • listPlist(1) > 粒子(0) > 位置 = 1,1

下一次迭代之后:

  • listPlist(0) > 粒子(0) > 位置 = 2,2
  • listPlist(1) > 粒子(0) > 位置 = 2,2
  • listPlist(2) > 粒子(0) > 位置 = 2,2

我不太确定如何解决这个问题。有谁知道为什么会发生这种情况?

最佳答案

据我从您的问题中了解到,问题在于您正在尝试复制引用项,这就是为什么您看到所有列表项都发生变化。

您将需要对这些列表/粒子进行深度克隆,以便它们不依赖于引用。

您可能必须向粒子对象添加新的复制方法或构造函数才能实现此目的。

类似的东西

public class Particle
{
    public int SomeField;

    public Particle Copy()
    {
        return new Particle { SomeField = this.SomeField };
    }   

    public Particle(Particle copyFrom)
    {
        this.SomeField = copyFrom.SomeField;
    }
}

然后您可以创建原始列表的副本,例如

List<Particle> copyList = new List<Particle>(originalList.Select(c => c.Copy));

关于c# - 在 Windows 窗体 C# 中,更新 List<List<T>> 更新已输入的 List<T> 条目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11642724/

相关文章:

c# - 将两个不同属性绑定(bind)在一起的简单方法?

c - 在 C 列表上添加尾节点

list - 模式匹配 x::xs 没有在 F# 中相应地拆分列表?

c# - 如何在 while 循环中跳过多次迭代

c# - C# 3.0 中属性 {get, set} 方法的用途是什么

c# - 如何替换 Sendgrid 模板变量? (在 C# 中)

python - 如何在双向链表中实现插入方法?

c# - 我可以将 Lucene 索引存储在数据库或文件系统以外的其他位置吗?

c# - 在datagridview中如何卡住2列?

c# - WebServices 失败,因为 (400) Bad Request because of special character