【发布时间】:2016-08-20 23:34:29
【问题描述】:
我正在尝试使用 profobuf-net,但是尽管根据文档(我正在使用 2.0.0.668 版本进行测试),它似乎支持从版本 2 开始的“引用对象”,但我不明白工作。
为了让问题更容易理解,下面是一个简短的示例代码:
private static void Test()
{
MainObject mainObject = new MainObject();
TestObject testObject = new TestObject();
ObjectByReference objectByReference = new ObjectByReference();
mainObject.TestObjects.Add(testObject);
mainObject.ObjectByReferences.Add(objectByReference);
testObject.ObjectByReference = objectByReference;
// Make sure the reference is the same before serialization.
Debug.Assert(testObject.ObjectByReference == objectByReference);
byte[] buf;
using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
{
Serializer.Serialize(ms, mainObject);
buf = ms.ToArray();
}
// --> Deserialize.
using (System.IO.MemoryStream ms = new System.IO.MemoryStream(buf))
{
mainObject = Serializer.Deserialize<MainObject>(ms);
}
testObject = mainObject.TestObjects[0];
objectByReference = mainObject.ObjectByReferences[0];
// Fails as now the reference suddenly is not the same anymore!
Debug.Assert(testObject.ObjectByReference == objectByReference);
}
[ProtoContract]
class MainObject
{
[ProtoMember(1)]
public List<TestObject> TestObjects = new List<TestObject>();
[ProtoMember(2)]
public List<ObjectByReference> ObjectByReferences = new List<ObjectByReference>();
}
[ProtoContract]
class TestObject
{
[ProtoMember(1)]
public ObjectByReference ObjectByReference { get; set; }
}
[ProtoContract(AsReferenceDefault = true)]
class ObjectByReference
{
}
如您所见,我正在为 ObjectByReference 类使用 AsReferenceDefault = true 属性,但这似乎没有任何效果:
在 Test 函数的最后一行测试仍然失败,因为这两个对象在反序列化后不再引用相等。
为什么会这样? 我做错了什么?
【问题讨论】:
-
很抱歉打扰,但我真的很纠结这个问题。我也将它作为错误发布在这里:github.com/mgravell/protobuf-net/issues/116,但还没有得到任何回复。其他人没有这个问题吗?
标签: c# protobuf-net