简体   繁体   中英

Storing array in a c# data structure so it has behaves like a value

The following code is designed so that if I change the array assigned to one node it will not affect the other node.

My question is: Is there a more "idiomatic" way to accomplish this?

void Main()
{
    var arr = new [] { 1, 2, 3 };

    var node1 = new Node();
    node1.Children = arr;

    var node2 = new Node();
    node2.Children = arr;

    node1.Children[0] = 9; // node2 SHOULD NOT be affected by this

    node1.Dump();
    node2.Dump();
}

class Node
{
    private int[] children;

    public int[] Children 
    { 
        get { return children; } 
        set 
        { 
            children = new int[value.Length];
            value.CopyTo(children, 0);
        }
    }
}

What about this [EDITED] :

class Node
{
    private int[] _children;

    public Node(int[] children)
    {
       this._children = (int[])children.Clone();//HERE IS THE IDEA YOU ARE LOOKING FOR
    }

    public int this[int index]
    {
        get { return this._children[index]; }
        set { this._children[index] = value; }
    }
}

I think you would be better off changing the array object copy semantics rather than adding features to the Node class to support this. Fortunately there is already a class with the semantics you are looking for: List.

This simplifies the Node class:

class Node
{
    public List<int> Children { get; set; }
}

The result:

static void Main(string[] args)
{
    var arr = new[] { 1, 2, 3 };

    var node1 = new Node
    {
        Children = new List<int>(arr)
    };

    var node2 = new Node
    {
        Children = new List<int>(node1.Children)
    };

    node1.Children[0] = 9; // node2 SHOULD NOT be affected by this

    Console.WriteLine("First element node1:{0}, first element node2:{1}",
        node1.Children[0], node2.Children[0]);            
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM