【问题标题】:Cloning independent instance克隆独立实例
【发布时间】:2014-05-07 02:00:41
【问题描述】:

这段代码的结果是“1”和“2”。当我拆分 Foo "a" 时,它会生成一个实例 "b" 以及我对 "b" 所做的一切,它也会发生在 "a" 上。 是否有任何解决方案可以返回一个完全独立的 Foo 实例?所以我的代码的结果是“1”和“1”。

using System.IO;
using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {

        Baar b0 = new Baar();
        Baar b1 = new Baar();
        Baar b2 = new Baar();
        Baar b3 = new Baar();
        Foo a = new Foo(200);
        a.addBaar(b0);

        Console.WriteLine(a.baars.Count);
        Foo b = a.split(100);

        b.addBaar(b1) ;      
        Console.WriteLine(a.baars.Count);

    }
}

class Foo
{
    public int amount;
    public List<Baar> baars = new List<Baar>();
    public Foo(int amount)
    {
        this.amount = amount;
    }

    private Foo(int amount, List<Baar> baars)
    {
        this.amount = amount;
        this.baars = baars;
    }

    public void addBaar(Baar baar)
    {
        this.baars.Add(baar);

    }

    public Foo split(int amount)
    {
        int diff = this.amount - amount;
        this.amount = amount;
        return new Foo(diff, this.baars);
    }
}

class Baar
{

    public Baar()
    {

    }
}

【问题讨论】:

  • "这段代码的结果是 "1" 和 "2"。... 所以我的代码的结果是 "1" 和 "2"。" -- 是其中一个错字,还是您的代码已经完成了您想要的操作?
  • Deep cloning objects 的可能重复项
  • 是的,这是一个错字。哈哈。我已经更正了。
  • 我已经编辑了你的标题。请参阅“Should questions include “tags” in their titles?”,其中的共识是“不,他们不应该”。

标签: c# clone


【解决方案1】:

您的split 方法正在传递对底层baars 列表的相同 的引用。这可以通过以下方式简单地证明:

List<int> a = new List<int>();
a.Add(1);

Console.WriteLine(a.Count); //1

List<int> b = a;
b.Add(2);

Console.WriteLine(b.Count); //2
Console.WriteLine(a.Count); //2
Console.WriteLine(Object.ReferenceEquals(a, b)); //true

相反,您想传递该列表的副本

public Foo split(int amount)
{
    int diff = this.amount - amount;
    this.amount = amount;
    List<Baar> baarsCopy = new List<Baar>(this.baars); //make a copy
    return new Foo(diff, baarsCopy); //pass the copy
}

编辑:除此之外,我不知道您是要复制该列表中的 Baar 项目还是传递/共享对相同 Baar 实例的引用。这取决于您和您的应用程序使用情况。

【讨论】:

    【解决方案2】:

    看起来您在谈论“深度克隆”对象。这个问题已经回答了很多次了。

    How do you do a deep copy of an object in .NET (C# specifically)?

    Deep cloning objects

    【讨论】:

      猜你喜欢
      • 2015-09-23
      • 2018-09-22
      • 2011-01-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-22
      • 2021-07-23
      • 1970-01-01
      相关资源
      最近更新 更多