我想为包含类似类型子项列表的 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 次,一次又一次。
将子项作为嵌套数组添加到序列化程序将在反序列化时返回正确大小的数组,但所有元素都将为空。
但是,将类型从嵌套数组更改为嵌套列表将在调用子项的构造函数后神奇地修复空元素。
我想知道的是:
- 嵌套列表有什么特别之处?
- 用这样的递归结构序列化一个类的推荐方法是什么?
更新:
似乎还有一个额外的接口,IDeserializationCallback.OnDeserialization,它在反序列化发生后调用(调用顺序是不确定的)。您可以将反序列化的数组存储在构造函数的临时成员变量中,然后将其分配给此方法中的列表。除非我遗漏了什么,否则这似乎不太理想,因为您必须使用临时变量使您的实现变得混乱。