There is such a class with a collection:

public class Animal { public string Sound { get; set; } } [Serializable] public class Example { public ObservableCollection<Animal> animals { get; set; } = new ObservableCollection<Animal>() { new Animal() {Sound = "Гав"}, new Animal() {Sound = "Мяу"}, new Animal() {Sound = "Кря"} }; public Example() { } } 

Serialize to XML and everything goes fine. The file looks like this:

 <?xml version="1.0"?> <Example xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <animals> <Animal> <Sound>Гав</Sound> </Animal> <Animal> <Sound>Мяу</Sound> </Animal> <Animal> <Sound>Кря</Sound> </Animal> </animals> </Example> 

But after deserialization, there are 6 elements in the collection, instead of 3. As I understand it, this happens because when you create an instance of a class, the original 3 elements are added to the collection due to the constructor, and then 3 more are added when deserializing.

How to make sure that after deserialization there is nothing extra in the collection?

  • And what if you bring initialization to the default constructor? - iluxa1810
  • @ iluxa1810, Does not help. It helped to make the initialization of the collection in a separate method, but maybe there is some other option. - trydex
  • I think the attributes I described in the answer should help. - iluxa1810
  • @ iluxa1810, Thank you, I will understand! - trydex
  • one
    A pragmatic solution is to remove the addition of elements, and add them after the designer has completed. - VladD

1 answer 1

There is a solution to the forehead:

  1. Create a separate constructor, which is given the input path to XML. We load XML into memory and we pass handles on it to perform the correct initialization.
  2. Make an additional named constructor for the user and add logic to fill the Tula collection. This constructor will create the object users and there will be initialization of the collection with initial values, and the deserializer will use the default constructor.

Maybe there are some interesting solutions, but these are the fastest in implementation.