What is protobuf-net SerializeWithLengthPrefix tag argument for?

后端 未结 1 908
心在旅途
心在旅途 2020-12-31 09:42

This method accepts as the last argument an integer, but I\'m not sure I understand what I would use it for exactly.

Serializer.SerializeWithLengthPrefix(str         


        
相关标签:
1条回答
  • 2020-12-31 10:46

    Basically, it is an additional marker that can be (although does not have to be) used to note the "type" of the message being added, since the presumption (when using the *WithLengthPrefix approach) is that there are multiple messages in the same stream.

    By being included, it also means that the entire composite stream is itself an entirely valid protobuf message.

    Ways of using this:

    • you can serialize a List<Foo>, and then repeatedly deserialize (with-length-prefix) individual Foo items, or vice-versa
    • with a heterogeneous set of objects, you can use the Serializer.NonGeneric API to allow type-resolution based on the tag, i.e. the code equivalent of "if 1 then Invoice; if 2 then Order, if 3 then skip it, if 4 then Customer", etc - this is especially useful if using a NetworkStream as a message-sending device. This approach (using a different tag per type) allows you to read objects off the stream, and deserialize them correctly, without knowing in advance the type of the next message

    It is possible to omit this if you want - just pass zero (IIRC). This will save (typically) a byte per message appended, but: it means that the stream is no longer a valid protobuf itself. It can still be read, of course, by passing zero when reading.

    0 讨论(0)
自定义标题
段落格式
字体
字号
代码语言
提交回复
热议问题