将数组存储在c#数据结构中,使其行为类似于值

时间:2013-03-30 04:38:09

标签: c# arrays

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

我的问题是:是否有更“惯用”的方法来实现这一目标?

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

2 个答案:

答案 0 :(得分:3)

[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; }
    }
}

答案 1 :(得分: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]);            
}