I would like to track object references across multiple chunks of serialized objects. The serializers I know can track references, but only to serialize one graph as a whole at once. I want to partially serialize a graph and then later serialize another part of it or update some objects from the graph.
I think the code below explains my problem quite well - I'm searching for a Serializer that would print a "Success" if it was used here.
[Serializable]
class TestClass
{
public string Identifier;
public TestClass Reference;
}
class Program
{
static void Main(string[] args)
{
//some test data
TestClass t1 = new TestClass();
t1.Identifier = "t1";
TestClass t2 = new TestClass();
t2.Reference = t1;
t2.Identifier = "t2";
BinaryFormatter formatter = new BinaryFormatter(); //replace this with something that works ^^
MemoryStream stream = new MemoryStream(1024);
formatter.Serialize(stream, t1);
//possibly do lots of things inbetween these two, including,
//but not limited to, switching streams, writing other things
//on the stream etc.
formatter.Serialize(stream, t2);
stream.Position = 0;
object copy1 = formatter.Deserialize(stream);
object copy2 = formatter.Deserialize(stream);
if (((TestClass)copy2).Reference == copy1)
{
Console.WriteLine("Success");
}
else
{
Console.WriteLine("Failure");
}
Console.ReadLine();
}
}
My use case is essentially that I want to send objects over the network and keep the references intact. I have looked into protobuf-net and have written some workarounds around this issue, but they are getting out of hands in terms of complexity. My question is: is there a (good) serialization library that allows me to track references across one call of the deserialization method? Or am I missing some simple technique to archieve this with existing serializers? Or do I have to write such a thing by myself?
EDIT: Clarification: This is networking for a game, so speed and compactness are an issue. That means XML/JSON serializers are a rather bad alternative.