Protobuf-net判断字段是否有值

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 )

  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值