我想为包含类似类型子项列表的C#类实现ISerializable。考虑以下示例:

using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;

namespace serialisation
{
    [Serializable]
    internal class Nested : ISerializable
    {
        public string Name { get; set; }

        public List<Nested> Children { get; set; }

        public Nested(string name)
        {
            Name = name;
            Children = new List<Nested>();
        }

        protected Nested(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context)
        {
            Name = info.GetString("Name");

            // This doesn't work:
            Nested[] children = (Nested[])info.GetValue("Children", typeof(Nested[]));
            Children = new List<Nested>(children);

            // This works:
            // Children = (List<Nested>)info.GetValue("Children", typeof(List<Nested>));
        }

        public void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context)
        {
            info.AddValue("Name", Name);

            // This doesn't work:
            info.AddValue("Children", Children.ToArray());

            // This works:
            //info.AddValue("Children", Children);
        }
    }

    internal class Program
    {
        private static void Main(string[] args)
        {
            // Generate a hierarchy
            Nested root = new Nested("root");
            Nested child1 = new Nested("child1");
            Nested child2 = new Nested("child2");
            Nested child3 = new Nested("child3");
            child1.Children.Add(child2);
            child1.Children.Add(child3);
            root.Children.Add(child1);

            Nested deserialized;
            BinaryFormatter binaryFmt = new BinaryFormatter();

            // Serialize
            using (var fs = new FileStream("Nested.xml", FileMode.OpenOrCreate))
            {
                binaryFmt.Serialize(fs, root);
            }

            // Deserialize
            using (var fs = new FileStream("Nested.xml", FileMode.OpenOrCreate))
            {
                deserialized = (Nested)binaryFmt.Deserialize(fs);
            }

            // deserialized.Children contains one null child
            Console.WriteLine("Original Name: {0}", root.Name);
            Console.WriteLine("New Name: {0}", deserialized.Name);
        }
    }
}


在上面的示例中,Nested.GetObjectData和Nested的序列化程序构造函数被调用4次,一次又一次。

将子级作为嵌套数组添加到序列化程序中时,将在反序列化时返回大小正确的数组,但是所有元素都将为null。

但是,将类型从Nested数组更改为Nested List将在调用子级的构造函数后神奇地修复了null元素。

我想知道的是:


嵌套列表有什么特别之处?
建议使用诸如此类的递归结构序列化类的方法是什么?


更新:

似乎还有一个附加接口IDeserializationCallback.OnDeserialization,它在反序列化发生之后被调用(调用顺序是不确定的)。您可以将反序列化的数组存储在构造函数中的temp成员变量中,然后在此方法中将其分配给列表。除非我缺少任何东西,否则这似乎不太理想,因为您必须使用temp var来使实现混乱。

最佳答案

我会使用复合模式。如果您要使用BinaryFormatter方法(如在Main中)和XmlSerializer方法,则下面的解决方案都可以解决。 CompositeComponent替换您的Nested类。

[Serializable()]
[XmlRoot("component", Namespace="", IsNullable=false)]
public partial class CT_Component
{
    [XmlAttribute("name")]
    public string Name { get; set;}
}

[Serializable()]
[XmlRoot("composite", Namespace="", IsNullable=false)]
public partial class CT_Composite
{
    [XmlElement("component", typeof(CT_Component))]
    [XmlElement("composite", typeof(CT_Composite))]
    public object[] Items { get; set; }

    [XmlAttribute("name")]
    public string Name { get; set; }
}


我是从以下xsd创建的,由于无法正确获得属性修饰,所以我总是从xsd转到生成的类。要点是递归CT_Composite类型:

<xs:element name="component" type="CT_Component" />
<xs:element name="composite" type="CT_Composite" />
<xs:complexType name="CT_Component">
  <xs:attribute name="name" type="xs:string" use="required" />
</xs:complexType>
<xs:complexType name="CT_Composite" >
  <xs:choice minOccurs="1" maxOccurs="unbounded">
    <xs:element ref="component" />
    <xs:element name="composite" type="CT_Composite" />
  </xs:choice>
  <xs:attribute name="name" type="xs:string" use="required" />
</xs:complexType>


序列化代码是相同的。变量声明:

var composite = new CT_Composite() {
            Name = "root",
            Items = new object[] {
                new CT_Composite() {
                    Name = "child1",
                    Items = new object[] {
                        new CT_Component() {Name="child2"},
                        new CT_Component() {Name="child3"}
                    } } } };


如果您对模式更为正统,则可以使用:

[Serializable()]
[XmlRoot("component", Namespace="", IsNullable=false)]
public class Component {
    [XmlAttribute("name")] public string Name { get; set;}
}

[Serializable()]
[XmlRoot("composite", Namespace="", IsNullable=false)]
public class Composite : Component {
    [XmlElement("component", typeof(Component))]
    [XmlElement("composite", typeof(Composite))]
    public object[] Items { get; set; }
}

10-05 21:08
查看更多