克隆独立实例

时间:2014-05-07 02:00:42

标签: c# clone

此代码的结果是" 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()
    {

    }
}

2 个答案:

答案 0 :(得分: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个实例的引用。这取决于您和您的应用程序使用情况。

答案 1 :(得分:0)

看起来你在谈论&#34;深度克隆&#34;对象。这个问题已经被回答了很多次。

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

Deep cloning objects