Stavo rintracciando un bug e ho notato che Newton JSON aggiungerà gli articoli a un List<>
che è stato inizializzato nel costruttore predefinito. Ho fatto un po 'più di scavo e discusso con alcune persone nella chat in C# e abbiamo notato che questo comportamento non si applica a tutti gli altri tipi di raccolta.Spiegazione per ObjectCreationHandling utilizzando Newton JSON?
https://dotnetfiddle.net/ikNyiT
using System;
using Newtonsoft.Json;
using System.Collections.Generic;
using System.Collections.ObjectModel;
public class TestClass
{
public Collection<string> Collection = new Collection<string>(new [] { "ABC", "DEF" });
public List<string> List = new List<string>(new [] { "ABC", "DEF" });
public ReadOnlyCollection<string> ReadOnlyCollection = new ReadOnlyCollection<string>(new [] { "ABC", "DEF" });
}
public class Program
{
public static void Main()
{
var serialized = @"{
Collection: [ 'Goodbye', 'AOL' ],
List: [ 'Goodbye', 'AOL' ],
ReadOnlyCollection: [ 'Goodbye', 'AOL' ]
}";
var testObj = JsonConvert.DeserializeObject<TestClass>(serialized);
Console.WriteLine("testObj.Collection: " + string.Join(",", testObj.Collection));
Console.WriteLine("testObj.List: " + string.Join(",", testObj.List));
Console.WriteLine("testObj.ReadOnlyCollection: " + string.Join(",", testObj.ReadOnlyCollection));
}
}
uscita:
testObj.Collection: ABC,DEF
testObj.List: ABC,DEF,Goodbye,AOL
testObj.ReadOnlyCollection: Goodbye,AOL
Come si può vedere la proprietà Collection<>
non è influenzato dalla deserializzazione, il List<>
viene aggiunto e ReadOnlyCollection<>
è sostituito. È questo comportamento previsto? Qual è stato il ragionamento?
Sospetto che la risposta sarebbe "solo perché", inoltre sarebbe interessante sapere se c'è un motivo dietro il comportamento per List/Collection (il comportamento di ReadOnlyCollection è in qualche modo autoesplicativo dal mio punto di vista). Nota a margine: considera l'aggiornamento del titolo per essere più specifico - "curioso" è un po 'difficile da indovinare se uno vorrebbe trovare questo in base al problema ... –
@AlexeiLevenkov - Sto avendo alcuni problemi a capire le sfumature tra ReadOnlyCollection e Collection. Il problema sembra essere con l'impostazione ObjectCreationHandling e così l'ho aggiunto al titolo. –
Questo problema è stato discusso anche nella [chat room C#] (http://chat.stackoverflow.com/transcript/message/20857312#20857312). –