Copy annotations when cloning elements (#2442)

This commit is contained in:
James Newton-King
2021-01-01 19:25:57 +13:00
committed by GitHub
parent 0cf47a4687
commit ff5ffb2832
4 changed files with 66 additions and 0 deletions
@@ -257,6 +257,57 @@ namespace Newtonsoft.Json.Tests.Linq
Assert.AreEqual(new Uri("http://www.google.com/"), i);
}
[Test]
public void AnnotationsAreCopied()
{
JObject o = new JObject();
o.AddAnnotation("string!");
AssertCloneCopy(o, "string!");
JProperty p = new JProperty("Name", "Content");
p.AddAnnotation("string!");
AssertCloneCopy(p, "string!");
JArray a = new JArray();
a.AddAnnotation("string!");
AssertCloneCopy(a, "string!");
JConstructor c = new JConstructor("Test");
c.AddAnnotation("string!");
AssertCloneCopy(c, "string!");
JValue v = new JValue(true);
v.AddAnnotation("string!");
AssertCloneCopy(v, "string!");
JRaw r = new JRaw("raw");
r.AddAnnotation("string!");
AssertCloneCopy(r, "string!");
}
[Test]
public void MultipleAnnotationsAreCopied()
{
Version version = new Version(1, 2, 3, 4);
JObject o = new JObject();
o.AddAnnotation("string!");
o.AddAnnotation(version);
JObject o2 = (JObject)o.DeepClone();
Assert.AreEqual("string!", o2.Annotation<string>());
Assert.AreEqual(version, o2.Annotation<Version>());
o2.RemoveAnnotations<Version>();
Assert.AreEqual(1, o.Annotations<Version>().Count());
Assert.AreEqual(0, o2.Annotations<Version>().Count());
}
private void AssertCloneCopy<T>(JToken t, T annotation) where T : class
{
Assert.AreEqual(annotation, t.DeepClone().Annotation<T>());
}
#if !NET20
[Test]
public void Example()
+2
View File
@@ -117,6 +117,8 @@ namespace Newtonsoft.Json.Linq
AddInternal(i, child, false);
i++;
}
CopyAnnotations(this, other);
}
internal void CheckReentrancy()
+12
View File
@@ -2704,5 +2704,17 @@ namespace Newtonsoft.Json.Linq
}
}
}
internal void CopyAnnotations(JToken target, JToken source)
{
if (source._annotations is object[] annotations)
{
target._annotations = annotations.ToArray();
}
else
{
target._annotations = source._annotations;
}
}
}
}
+1
View File
@@ -64,6 +64,7 @@ namespace Newtonsoft.Json.Linq
public JValue(JValue other)
: this(other.Value, other.Type)
{
CopyAnnotations(this, other);
}
/// <summary>