问题描述
在 Protobuf3 中,零是数字类型的默认值,因此它们在序列化时会被过滤掉.
In Protobuf3 zero is the default value for numeric types, and so they are filtered out when serialized.
我有一个应用程序,我只需要在它发生变化时发送一个值.例如,x 是 1,现在 x 是 0,发送这个值.
I have an application where I need to send a value only when it has changed. For example, x was 1, now x is 0, send this value.
不可能只发送增量,例如 -1,因为其中一些值是浮点数或双精度数,我们不想产生错误.
It isn't possible to send only the delta, eg -1, because some of these values are floats or doubles, and we do not want to accrue errors.
在我需要序列化的某些类中有超过 200 个不同的变量,因此诸如添加一个布尔值来标记哪些字段已更改"之类的解决方案是可能的,但并不有趣.其他需要大量工作或处理的建议也是不可取的.
There are over 200 different variables in some classes I need to serialize, so solutions like "add a boolean to flag which fields have changed" are possible but not fun. Other suggestions that have a large amount of per-field work or processing are undesirable too.
是否有一种简单的机制可以告诉 protobuf3 明确保留一个值,即使它是默认值?
Is there a simple mechanism to tell protobuf3 to explicitly keep a value even though it is the default value?
可能的解决方案:
- 每次都发送整个课程.这里的主要缺点是某些字段可能包含大量数据.
- 在架构中使用布尔值已更改"来指示变量是否已更改,即使它是 0
- 使用魔法值.可怕的想法,但可能.不打算这样做.
推荐答案
如果需要区分 0
和 null
那么可以使用 proto3 封装类型:https://developers.google.com/protocol-buffers/docs/reference/csharp-generated#wrapper_types这种情况有特殊的包装类型:StringWrapper
、Int32Wrapper
等.与 C# 值类型(Int32Wrapper、DoubleWrapper、BoolWrapper
等)对应的所有包装器类型都映射到 Nullable
,其中 T
是相应的不可为空类型.
If you need to distinguish 0
and null
then you can use proto3 wrapper types: https://developers.google.com/protocol-buffers/docs/reference/csharp-generated#wrapper_typesThere are special wrapper types for such case: StringWrapper
, Int32Wrapper
and etc. All of the wrapper types that correspond to C# value types (Int32Wrapper, DoubleWrapper, BoolWrapper
etc) are mapped to Nullable<T>
where T
is the corresponding non-nullable type.
这篇关于在 protobuf3 中发送显式零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!