金庆的专栏

  C++博客 :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理 ::
  423 随笔 :: 0 文章 :: 454 评论 :: 0 Trackbacks
Protobuf-net判断字段是否有值

Unity3d使用Protobuf-net序列化数据与服务器通信,
但是发现默认情况下,Protobuf-net生成的cs文件中没有接口判断可选参数是否有值。
需有添加 -p:detectMissing 参数才能生成判断接口。
在C++中生成 has_*() 接口,在C#中是 *Specified() 接口。

例如 rpc.proto:
message RpcRequest {
    optional uint32 id = 1;  // One-way request has no id.
    ...
}


生成rpc.cs:
protogen -i:rpc.proto -o:%OUT_DIR%/rpc.cs

  public partial class RpcRequest : global::ProtoBuf.IExtensible
  {
    private uint _id = default(uint);
    public uint id
    {
      get { return _id; }
      set { _id = value; }
    }
    ...
  }  

添加 -p:detectMissing 参数后:
protogen -i:rpc.proto -o:%OUT_DIR%/rpc.cs -p:detectMissing

  public partial class RpcRequest : global::ProtoBuf.IExtensible
  {
    private uint? _id;
    public uint id
    {
      get { return _id?? default(uint); }
      set { _id = value; }
    }
    public bool idSpecified
    {
      get { return this._id != null; }
      set { if (value == (this._id== null)) this._id = value ? this.id : (uint?)null; }
    }
    private bool ShouldSerializeid() { return idSpecified; }
    private void Resetid() { idSpecified = false; }
    ...
  }

参考:
protobuf-net missing has_ function for optional fields?.
( http://stackoverflow.com/questions/18889249/protobuf-net-missing-has-function-for-optional-fields )
Issue 406:     has_ functions missing in protobuf-net?
( https://code.google.com/p/protobuf-net/issues/detail?id=406 )
posted on 2015-05-20 19:47 金庆 阅读(2530) 评论(0)  编辑 收藏 引用 所属分类: 9. 其它

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理