protobuf网:序列化空List [英] protobuf-net: Serializing an empty List

查看:316
本文介绍了protobuf网:序列化空List的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们有一些问题,序列化空列表。 这里采用CF 2.0约code。在.NET

we have some problems with serializing an empty list. here some code in .NET using CF 2.0

//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);
}

我们有一个例外,当我们试图对流(bytes.length超出范围)编写。 但是,类型与空List不应该是0字节,右(类型的信息?)?

we got a exception, when we try to write on the stream (bytes.length out of range). But a type with an empty List should not be 0 bytes, right (type-information?)?

我们需要这种类型的发送,因为在响应从服务器中的消息为我们的客户。

We need this type of sending, because in the Response are the messages from the Server for our client.

推荐答案

钢丝格式(由谷歌定义 - 不是在我的控制),只发送数据的项目的。它使一个的列表和列表中没有区别。所以,如果没有要发送的数据 - 是的,长度为0(这是一个很节俭的格式;-p)

The wire format (defined by google - not inside my control!) only sends data for items. It makes no distinction between an empty list and a null list. So if there is no data to send - yes, the length is 0 (it is a very frugal format ;-p).

议定书缓冲器不包括在电线上的任何类型的元数据。

Protocol buffers do not include any type metadata on the wire.

下面的另一个常见的​​问题是,你可能会认为你的列表属性会自动初始化为空的,但它不会(除非你的code这么做,或许在外地初始化或构造函数)。

Another common gotcha here is that you might assume your list property is automatically instantiated as empty, but it won't be (unless your code does it, perhaps in a field initializer or constructor).

下面是一个可行的破解:

Here's a workable hack:

[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>();}}
    }
}

哈克也许,但它应该工作。你也可能会失去产品设置,如果你想和刚落布尔

Hacky maybe, but it should work. You could also lose the Items "set" if you want and just drop the 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 { }
    }

这篇关于protobuf网:序列化空List的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆