protobuf-net - 重写内置类型的序列化方法

标签 protobuf-net

我需要在运行时或至少在模型初始化期间为某些内置类型(例如 DateTime)切换不同的序列化方法。做到这一点的最佳方法是什么? 我尝试使用自定义模型(RuntimeTypeModel.Add(typeof(DateTime), false).SetSurrogate(typeof(uint)))代理它们,但收到错误“此类型的数据具有内置行为,并且无法添加到模型中”。

最佳答案

说实话,我并没有认真考虑过这种情况。对于大多数“内置行为”类型来说,改变实现是一个非常非常糟糕的主意,因为它是 protobuf 特定的一部分;然而,在 DateTime 的情况下, TimeSpan , DecimalGuid或许还有可以支持的替代布局。我能问一下您到底想在这里做什么吗?因为可能有更好的方法来做到这一点。同样重要的是:其大小是多少?如果只是少数情况,那么 shim 属性可能更好,例如:

public DateTime When {get;set;}
[ProtoMember(4)]
private uint WhenSerialized {
   get { return YourConverter.FromDateTime(When); }
   set { When = YourConverter.ToDateTime(value); }
}

也可以为这些类型启用“代理”处理,但您不能使用代理直接访问 uint (不过,您可以使用代理来获取具有 structclassuint )。

关于protobuf-net - 重写内置类型的序列化方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16671621/

相关文章:

c# - 开始使用 protobuf-net

xamarin.ios - 如何将 Protobuf-Net 与 MonoTouch 结合使用?

protobuf-net - .net 4 中的链接错误

protocol-buffers - Google protobuf 3 : deprecated a field, 但无法删除依赖项?

c# - protobuf 网络 : how to annotate properties of derived type?

Protobuf-net 序列化错误 = "The type cannot be changed once a serializer has been generated"

c# - ProtoBuf WCF 行为的配置错误

c# - 尝试读取流末尾时没有无参数构造函数异常

c# - 使用 WCF 通过 HTTP GET Protocol Buffer

protocol-buffers - 在预构建事件中使用 protogen 从 .proto 文件生成 c# 文件