问题
code is here:
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");
result is
responseMsg this is local server
response
ProtoBuf-net can not Deserialize what it Serialized. it's really a strange thing
回答1:
You need to rewind the stream to the beginning by resetting its Position before you can read from it:
serverStream.Position = 0;
var response = ProtoBuf.Serializer.Deserialize<ResponseMessage>(serverStream);
Sample fiddle.
来源:https://stackoverflow.com/questions/40275433/protobuf-net-deserialize-does-not-work