c# – 序列化循环引用对象的最佳方法是什么?

前端之家收集整理的这篇文章主要介绍了c# – 序列化循环引用对象的最佳方法是什么?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
更好的是文本格式.最好的是json,有一些标准指针.二进制也不错.记住,在过去,肥皂已经成为了这一点.你的建议是什么?

解决方法

没有任何问题 binary
  1. [Serializable]
  2. public class CircularTest
  3. {
  4. public CircularTest[] Children { get; set; }
  5. }
  6.  
  7. class Program
  8. {
  9. static void Main()
  10. {
  11. var circularTest = new CircularTest();
  12. circularTest.Children = new[] { circularTest };
  13. var formatter = new BinaryFormatter();
  14. using (var stream = File.Create("serialized.bin"))
  15. {
  16. formatter.Serialize(stream,circularTest);
  17. }
  18.  
  19. using (var stream = File.OpenRead("serialized.bin"))
  20. {
  21. circularTest = (CircularTest)formatter.Deserialize(stream);
  22. }
  23. }
  24. }

一个DataContractSerializer也可以处理循环引用,你只需要使用一个特殊的构造函数并指出它,它将吐出XML:

  1. public class CircularTest
  2. {
  3. public CircularTest[] Children { get; set; }
  4. }
  5.  
  6. class Program
  7. {
  8. static void Main()
  9. {
  10. var circularTest = new CircularTest();
  11. circularTest.Children = new[] { circularTest };
  12. var serializer = new DataContractSerializer(
  13. circularTest.GetType(),null,100,false,true,// <!-- that's the important bit and indicates circular references
  14. null
  15. );
  16. serializer.WriteObject(Console.OpenStandardOutput(),circularTest);
  17. }
  18. }

最新版本的Json.NET支持循环引用以及JSON:

  1. public class CircularTest
  2. {
  3. public CircularTest[] Children { get; set; }
  4. }
  5.  
  6. class Program
  7. {
  8. static void Main()
  9. {
  10. var circularTest = new CircularTest();
  11. circularTest.Children = new[] { circularTest };
  12. var settings = new JsonSerializerSettings
  13. {
  14. PreserveReferencesHandling = PreserveReferencesHandling.Objects
  15. };
  16. var json = JsonConvert.SerializeObject(circularTest,Formatting.Indented,settings);
  17. Console.WriteLine(json);
  18. }
  19. }

生产:

  1. {
  2. "$id": "1","Children": [
  3. {
  4. "$ref": "1"
  5. }
  6. ]
  7. }

我想这就是你所问的问题.

猜你在找的C#相关文章