[英]Storing array in a c# data structure so it has behaves like a value
設計以下代碼,以便如果我更改分配給一個節點的數組,則不會影響另一節點。
我的問題是:是否有更“慣用”的方式來實現這一目標?
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);
}
}
}
那這個[編輯] :
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; }
}
}
我認為您最好更改數組對象副本的語義,而不是向Node類添加功能以支持此功能。 幸運的是,已經有一個具有您要查找的語義的類:列表。
這簡化了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]);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.