C # Xml Serializer deserializes list to 0 instead of zero

I am confused about how it XmlSerializerworks behind the scenes. I have a class that deserializes XML into an object. What I see are the following two elements that are NOT part of the Xml description.

[XmlRootAttribute("MyClass", Namespace = "", IsNullable = false)]
public class MyClass
{
    private string comments;
    public string Comments
    {
        set { comments = value; }
        get { return comments; }
    }

    private System.Collections.Generic.List<string> tests = null;
    public System.Collections.Generic.List<string> Tests
    {
        get { return tests; }
        set { tests = value; }
    }
}

Take the following XML as an example:

<MyClass>
  <SomeNode>value</SomeNode>
</MyClass>

You have noticed that tests and comments are NOT part of XML.

When this XML is deserialized, the comments are null (which is expected), and Tests is an empty list with the number 0.

If someone can explain this to me, it will be very grateful. I would prefer that if <Tests>absent from XML, the list should remain empty, but if there is a (possibly empty) node <Tests />, the list should be highlighted.

+4
1

, , , , , List<T>, XmlSerializer . , . , , XML Deserialization , , , XmlSerializer , , - , . , Microsoft .

, , . , XmlSerializer , . , XmlSerializer, -, set setter. -, , :

[XmlRootAttribute("MyClass", Namespace = "", IsNullable = false)]
public class MyClass
{
    private string comments;
    public string Comments
    {
        set { comments = value; }
        get { return comments; }
    }

    private System.Collections.Generic.List<string> tests = null;

    [XmlIgnore]
    public System.Collections.Generic.List<string> Tests
    {
        get { return tests; }
        set { tests = value; }
    }

    [XmlArray("Tests")]
    public string[] TestsArray
    {
        get
        {
            return (Tests == null ? null : Tests.ToArray());
        }
        set
        {
            if (value == null)
                return;
            (Tests = Tests ?? new List<string>(value.Length)).AddRange(value);
        }
    }
}

. , , Tests .

+2

Source: https://habr.com/ru/post/1682439/


All Articles