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 )
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 )