为什么 XElement 的行为不像引用类型?

Obs*_*ian 6 c# xml linq

我注意到这XElement是一个类,所以我尝试了类似的东西:

var doc = new XDocument(
    new XDeclaration("1.0", "utf8", "yes"),
    new XElement("Root")
    );
var root = doc.Root;
var com = new XElement("Component", new XAttribute("name", "arm"));
root.Add(com);
root.Add(com);
root.Add(com);
com.Add(new XAttribute("type", 1));

Console.WriteLine(doc);
Run Code Online (Sandbox Code Playgroud)

但输出是:

<Root>
  <Component name="arm" type="1" />
  <Component name="arm" />
  <Component name="arm" />
</Root>
Run Code Online (Sandbox Code Playgroud)

我也试过SetAttributeValue(),得到了同样的结果。

为什么 type 属性只附加到第一个组件?

Ala*_*anK 1

我在下面给出了第二个答案 - 更好,因为它给出了具体的设计原因 - 但留下了这个答案,因为它证明内部复制已经发生。


作为一个类并不能提供关于该类如何行为或应该如何对待的线索。

使用调试器

每个节点的哈希码

每个节点都有不同的哈希值,因此必须假定为不同的对象(因此推测在 期间正在进行复制Add())。

如果您可以更改操作顺序,就可以解决问题

static void X()
{
  var doc = new XDocument(
    new XDeclaration("1.0", "utf8", "yes"),
    new XElement("Root")
  );
  var root = doc.Root;
  var com = new XElement("Component", new XAttribute("name", "arm"));
  com.Add(new XAttribute("type", 1));
  root.Add(com);
  root.Add(com);
  root.Add(com);

  Console.WriteLine(doc);
}
Run Code Online (Sandbox Code Playgroud)

给予

<Root>
  <Component name="arm" type="1" />
  <Component name="arm" type="1" />
  <Component name="arm" type="1" />
</Root>
Run Code Online (Sandbox Code Playgroud)