简体   繁体   English

序列化包含列表的T <T>

[英]Serialize T that contains List<T>

I want to serialize a MyClass , which is a class that contains a list MyClass . 我要序列化MyClass ,这是一个包含列表MyClass

In the XML, I want to write only myClass.Name , then when I deserialize it, I then find which MyClass should be in which other MyClass . 在XML中,我只想编写myClass.Name ,然后在反序列化时,然后找到哪个MyClass应该在其他MyClass I have the following code that properly serializes the list of MyClass into a list of string . 我有以下代码将MyClass列表正确序列化为string列表。 However, it doesn't deserialize the list of string. 但是,它不会反序列化字符串列表。

//List of actual object. It's what I use when I work with the object.
[XmlIgnore]
public List<TaskConfiguration> ChildTasks { get; set; }

//Used by the serializer to get the string list, and used
//by the serializer to deserialize the string list to.
[XmlArray("ChildTasks")]
public List<string> ChildTasksSurrogate
{
    get
    {
        List<string> childTaskList = new List<string>();

        if (ChildTasks != null)
            childTaskList.AddRange(ChildTasks.Select(ct => ct.Name).ToList());

        if (_childTasksSurrogate != null)
            childTaskList.AddRange(_childTasksSurrogate);

        //Clears it not to use it when it serializes.
        _childTasksSurrogate = null;
        return childTaskList;
    }
    set
    {
        _childTasksSurrogate = value;
    }
}

[XmlIgnore]
private List<string> _childTasksSurrogate;

As I said, the serialization works. 如我所说,序列化有效。 The problem lies with the deserialization. 问题在于反序列化。 After the deserialization, MyClass._childTasksSurrogate is null . 反序列化之后, MyClass._childTasksSurrogatenull

问题与XmlSerializer如何反序列化Xml有关:我认为XmlSerializer将分配整个属性(读取: myList = DeserializedList) ,而看起来它添加了所有元素(读取: myList.AddRange(DeserializedList)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM