0

设计以下代码是为了如果我更改分配给一个节点的数组,它不会影响另一个节点。

我的问题是:有没有更“惯用”的方式来实现这一点?

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);
        }
    }
}
4

2 回答 2

3

这个[编辑]怎么样:

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; }
    }
}
于 2013-03-30T05:13:51.180 回答
0

我认为您最好更改数组对象复制语义,而不是向 Node 类添加功能来支持这一点。幸运的是,已经有一个具有您正在寻找的语义的类:List。

这简化了 Node 类:

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

结果:

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]);            
}
于 2013-03-30T05:21:16.030 回答