[英]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. 我认为您最好更改数组对象副本的语义,而不是向Node类添加功能以支持此功能。 Fortunately there is already a class with the semantics you are looking for: List. 幸运的是,已经有一个具有您要查找的语义的类:列表。
This simplifies the Node class: 这简化了Node类:
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]);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.