【问题标题】:Protobuf-net object reference after deserialization not equal although AsReferenceDefault used尽管使用了 AsReferenceDefault,但反序列化后的 Protobuf-net 对象引用不相等
【发布时间】: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 函数的最后一行测试仍然失败,因为这两个对象在反序列化后不再引用相等。

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

【问题讨论】:

标签: c# protobuf-net


【解决方案1】:

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

例子:

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

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

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多