反序列化后的Protobuf-net对象引用虽然使用AsReferenceDefault,但不相等

时间:2015-10-12 20:06:14

标签: c# protobuf-net

我试图使用profobuf-net,但它似乎支持"通过引用对象"从版本2开始,根据文档(我使用版本2.0.0.668进行测试),我不能让它工作。

为了使问题易于理解,下面是一个简短的示例代码:

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
{
}

正如您所看到的,我使用了AsReferenceDefault = true类的ObjectByReference属性,但这似乎没有任何效果: 测试仍然在Test函数的最后一行失败,因为反序列化后两个对象不再相等。

为什么会这样? 我做错了什么?

1 个答案:

答案 0 :(得分:1)

您必须将字段标记为(AsReference = true)

示例:

[ProtoMember(1, AsReference = true)]
 public MyClas className;

[ProtoContract(AsReferenceDefault = true)]
public class MyClass
{

}