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

app*_*orm 8 c# serialization json

更好的是文本格式.最好的是json,有一些标准指针.二进制也不错.记住,在过去,肥皂已经成为了这一点.你的建议是什么?

Dar*_*rov 10

二进制没问题:

[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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

一个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);
    }
}
Run Code Online (Sandbox Code Playgroud)

最新版本的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);
    }
}
Run Code Online (Sandbox Code Playgroud)

生产:

{
  "$id": "1",
  "Children": [
    {
      "$ref": "1"
    }
  ]
}
Run Code Online (Sandbox Code Playgroud)

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