我一直试图理解如何使用ISerializable接口正确地实现循环引用。但是我连简单的形式都无法计算出来,我读过解释here。
但是我没有能够实现它,我也试图寻找一个例子,但没有结果。我检查了MSDN上的文档,但无法引用如何使用循环引用处理自定义序列化。
我尝试过的最简单的形式是双链接列表。
发布于 2014-02-02 01:18:49
序列化循环引用只需要一种策略来序列化整个对象图,仅此而已。对于双链接列表,您可以从第一个节点开始,然后只是序列化下一个节点,(前面的节点已经序列化了,所以没有什么可做的),然后当您想再次构建列表时,可以对每个节点依次(递归地)设置相同的前一个节点。
public class LinkList : ISerializable
{
public Node First { get; set; }
public Node Tail { get; set; }
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue("Firts", First);
}
public LinkList(SerializationInfo info, StreamingContext context)
{
First = info.GetValue("First", typeof(Node)) as Node;
First.PrevNode = null;
//do one one while set the Tail of this class and LinkList proeprty for each node
}
}
public class Node : ISerializable
{
public LinkList LinkList { get; set; }
public Node(SerializationInfo info, StreamingContext context)
{
Name = info.GetString("Name");
NextNode = info.GetValue("NextNode", typeof(Node)) as Node;
if(NextNode != null)
NextNode.PrevNode = this;
}
public Node PrevNode
{
get;
set;
}
public Node NextNode
{
get;
set;
}
public string Name
{
get;
set;
}
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue("Name", Name);
info.AddValue("Next", NextNode);
}
}发布于 2014-02-02 00:22:38
要使其正常工作,一个选项是向类中添加一个ID字段。创建与字段ID相关联的整数链接列表,并根据查找链接列表中ID的引用填充只读链接列表属性。
这方面的一个限制是,it列表中的每个对象在反序列化时都必须可用。
https://stackoverflow.com/questions/21505471
复制相似问题