Deserializing List with XmlSerializer Causing Extra Items

后端 未结 2 953
不知归路
不知归路 2020-12-06 17:08

I\'m noticing an odd behavior with the XmlSerializer and generic lists (specifically List). I was wondering if anyone has seen this before or knows w

相关标签:
2条回答
  • 2020-12-06 17:45

    It happens because you are initializing the List in the constructor. When you go to deserialize, a new ListTest is created and then it populate the object from state.

    Think of the workflow like this

    1. Create a new ListTest
    2. Execute the Constructor (add 1,2,3,4)
    3. Deserialize the xml state, and add 1,2,3,4 to the List

    A simple solution would be to init the object outside the scope of the constructor.

    public class ListTest
    {
        public int[] Array { get; set; }
        public List<int> List { get; set; }
    
        public ListTest()
        {
    
        }
    
        public void Init() 
        {
            Array = new[] { 1, 2, 3, 4 };
            List = new List<int>(Array);
        }
    }
    
    ListTest listTest = new ListTest();
    listTest.Init(); //manually call this to do the initial seed
    
    0 讨论(0)
  • 2020-12-06 17:52

    The issue is that you're defining the original 1,2,3,4 in the List in the default constructor. Your deserializer is adding to the list, not defining it.

    0 讨论(0)
提交回复
热议问题