bop*_*opa 28 .net c# serialization protobuf-net
我们在序列化一个空列表时遇到了一些问题.这里有一些使用CF 2.0的.NET代码
//Generating the protobuf-msg
ProtoBufMessage msg = new ProtoBufMessage();
msg.list = new List<AnotherProtobufMessage>();
// Serializing and sending throw HTTP-POST
MemoryStream stream = new MemoryStream();
Serializer.Serialize(stream, msg);
byte[] bytes = stream.ToArray();
HttpWebRequest request = createRequest();
request.ContentLength = bytes.Length ;
using (Stream httpStream = request.GetRequestStream())
{
httpStream.Write(bytes, 0, bytes.Length);
}
Run Code Online (Sandbox Code Playgroud)
当我们尝试在流上写入时(bytes.length超出范围),我们得到了一个异常.但是具有空列表的类型不应该是0字节,对(类型信息?)?
我们需要这种类型的发送,因为在响应中是来自服务器的消息给我们的客户端.
Mar*_*ell 32
有线格式(由谷歌定义 - 不在我的控制范围内!)只发送项目数据.它不区分空列表和空列表.因此,如果没有数据要发送 - 是的,长度为0(这是一种非常节俭的格式;-p).
协议缓冲区不包括线路上的任何类型元数据.
另一个常见的问题是你可能会认为你的list属性被自动实例化为空,但它不会(除非你的代码执行它,可能在字段初始化器或构造函数中).
这是一个可行的黑客:
[ProtoContract]
class SomeType {
[ProtoMember(1)]
public List<SomeOtherType> Items {get;set;}
[DefaultValue(false), ProtoMember(2)]
private bool IsEmptyList {
get { return Items != null && Items.Count == 0; }
set { if(value) {Items = new List<SomeOtherType>();}}
}
}
Run Code Online (Sandbox Code Playgroud)
哈基可能,但它应该工作.Items如果你愿意,你也可能会失去"集合",只需删除bool:
[ProtoMember(1)]
public List<SomeOtherType> Items {get {return items;}}
private readonly List<SomeOtherType> items = new List<SomeOtherType>();
[DefaultValue(false), ProtoMember(2)]
private bool IsEmptyList {
get { return items.Count == 0; }
set { }
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7542 次 |
| 最近记录: |