设计以下代码是为了如果我更改分配给一个节点的数组,它不会影响另一个节点。
我的问题是:有没有更“惯用”的方式来实现这一点?
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);
}
}
}