Domanda

The result of this code is "1" and "2". When i split Foo "a" it makes an instance "b" and everything what i do to "b", it happens to "a" too. Is there any solution to give back a compleatly independent instance of Foo? So the result of my code would be "1" and "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()
    {

    }
}
È stato utile?

Soluzione

Your split method is passing around a reference to the same underlying baars list. This can be demonstrated simply with:

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

Instead, you want to pass a copy of that list:

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
}

EDIT: Beyond that, I don't know if you want to make copies of the Baar items inside that list as well or pass around/share references to the same Baar instances. That's up to you and your application usage.

Altri suggerimenti

Looks like you are talking about "deep cloning" objects. That question has been answered plenty of times already.

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

Deep cloning objects

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top