开发者

How to serialize a non List<T> collection in protobuf-net?

Observe the following code:

[ProtoContract]
public class C
{
  [ProtoMember(1)]
  public IList<string> Tags { get; set; }
}

class Program
{
  static void Main()
  {
    var m = RuntimeTypeModel.Default;
    m.AutoCompile = true;
    m.Add(typeof(IList<string>), false).AddSubType(1, typeof(ObservableCollection<int>));

    var c = new C { Tags = new ObservableCollection<string> { "hello" } };
    using (var ms = new MemoryStream())
    {
      Serializer.Serialize(ms, c);
      ms.Position = 0;
      var c2 = Serializer.Deserialize<C>(ms);
      Debug.Assert(c.Tags.Count == c2.Tags.Count);
      Debug.Assert(c.Tags.GetType() == c2.Tags.GetType());
    }
  }
}

开发者_Go百科The last assertion fails, because c2.Tags is a regular List<T>, rather than ObservableCollection<T>. In effect, the AddSubType statement is ignored.

Is it possible to fix it without using surrogates?


Lists etc are mapped to the "repeated" syntax from the .proto spec. This embeds directly from the parent object directly. There is no facility to store any additional metadata.

The code has been tweaked to highlight this rather than silently ignore it.

You can specify the default concrete type to use, but only that.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜