ProtoBuf-net反序列化不起作用

时间:2016-10-27 03:05:16

标签: serialization protobuf-net

代码在这里:

        var responseMsg = new ResponseMessage()
        {
            code = ErrorCode.OK,
            type = MsgType.LOGIN,
            responseStr = "this is local server"
        };
        var serverStream = new MemoryStream();
        ProtoBuf.Serializer.Serialize(serverStream, responseMsg);
        Console.WriteLine($"responseMsg {responseMsg?.responseStr ?? "failed"}\n");

        var response =ProtoBuf.Serializer.Deserialize<ResponseMessage>(serverStream);
        Console.WriteLine($"response {response?.responseStr ?? "failed"}\n");

结果是

responseMsg this is local server

response 

ProtoBuf-net无法反序列化它的序列化内容。这真是一件奇怪的事情

1 个答案:

答案 0 :(得分:0)

您需要先重新设置Position之前将流回放到开头,然后才能从中读取:

serverStream.Position = 0;
var response = ProtoBuf.Serializer.Deserialize<ResponseMessage>(serverStream);

示例fiddle