gpt4 book ai didi

c# - LINQ to XML 克隆

转载 作者:数据小太阳 更新时间:2023-10-29 02:18:17 24 4
gpt4 key购买 nike

谁能解释一下原地址XElement street node为什么变了?看起来 customer1 持有对地址 XElement 的引用,但 customer2 和 customer3 已复制。

为什么原来的地址变了? (LINQPad 示例)

var address =
new XElement ("address",
new XElement ("street", "Lawley St"),
new XElement ("town", "North Beach")
);

var customer1 = new XElement ("customer1", address);
var customer2 = new XElement ("customer2", address);
var customer3 = new XElement ("customer3", address);

customer1.Element ("address").Element ("street").Value = "Another St";

Console.WriteLine (customer2.Element ("address").Element ("street").Value);
Console.WriteLine ();

address.Dump();
Console.WriteLine ();

customer1.Dump();
Console.WriteLine ();

customer2.Dump();
Console.WriteLine ();

customer3.Dump();

输出

Lawley St


<address>
<street>Another St</street>
<town>North Beach</town>
</address>


<customer1>
<address>
<street>Another St</street>
<town>North Beach</town>
</address>
</customer1>


<customer2>
<address>
<street>Lawley St</street>
<town>North Beach</town>
</address>
</customer2>


<customer3>
<address>
<street>Lawley St</street>
<town>North Beach</town>
</address>
</customer3>

最佳答案

来自问题:

It looks like customer1 holds a reference to the address XElement but customer2 and customer3 have taken copies.

是的,这正是发生的事情。来自docs for XElement contents :

When adding XNode or XAttribute objects, if the new content has no parent, then the objects are simply attached to the XML tree. If the new content already is parented and is part of another XML tree, then the new content is cloned, and the newly cloned content is attached to the XML tree.

在第一种情况下,address 没有父级,因此直接附加。之后,它确实有父级,所以首先克隆它。

关于c# - LINQ to XML 克隆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2629700/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com