IT博客汇
  • 首页
  • 精华
  • 技术
  • 设计
  • 资讯
  • 扯淡
  • 权利声明
  • 登录 注册

    Protobuf-net判断字段是否有值

    金庆发表于 2015-05-20 11:47:00
    love 0
    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 )


    金庆 2015-05-20 19:47 发表评论


沪ICP备19023445号-2号
友情链接