序列化循环引用对象的最佳方法是什么?
本文关键字:方法 是什么 最佳 循环 引用 对象 序列化 | 更新日期: 2023-09-27 18:09:30
最好是文本格式。最好是json,加上一些标准的指针。二进制也不错。记得在过去,肥皂有这个标准。你有什么建议?
二进制文件没有问题:
[Serializable]
public class CircularTest
{
public CircularTest[] Children { get; set; }
}
class Program
{
static void Main()
{
var circularTest = new CircularTest();
circularTest.Children = new[] { circularTest };
var formatter = new BinaryFormatter();
using (var stream = File.Create("serialized.bin"))
{
formatter.Serialize(stream, circularTest);
}
using (var stream = File.OpenRead("serialized.bin"))
{
circularTest = (CircularTest)formatter.Deserialize(stream);
}
}
}
DataContractSerializer也可以处理循环引用,你只需要使用一个特殊的构造函数并指出这一点,它就会吐出XML:
public class CircularTest
{
public CircularTest[] Children { get; set; }
}
class Program
{
static void Main()
{
var circularTest = new CircularTest();
circularTest.Children = new[] { circularTest };
var serializer = new DataContractSerializer(
circularTest.GetType(),
null,
100,
false,
true, // <!-- that's the important bit and indicates circular references
null
);
serializer.WriteObject(Console.OpenStandardOutput(), circularTest);
}
}
和Json的最新版本。. NET也支持JSON中的循环引用:
public class CircularTest
{
public CircularTest[] Children { get; set; }
}
class Program
{
static void Main()
{
var circularTest = new CircularTest();
circularTest.Children = new[] { circularTest };
var settings = new JsonSerializerSettings
{
PreserveReferencesHandling = PreserveReferencesHandling.Objects
};
var json = JsonConvert.SerializeObject(circularTest, Formatting.Indented, settings);
Console.WriteLine(json);
}
}
生产:
{
"$id": "1",
"Children": [
{
"$ref": "1"
}
]
}
我猜这就是你想问的。