如何序列化非 Listprotobuf-net 中的集合?
观察以下代码:
[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());
}
}
}
最后一个断言失败,因为 c2.Tags 是常规的 List
,而不是 ObservableCollection
。实际上,AddSubType 语句被忽略。
是否可以在不使用代理的情况下修复它?
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());
}
}
}
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
列表等映射到 .proto 规范中的“重复”语法。这直接从父对象直接嵌入。没有存储任何附加元数据的设施。
代码已被调整以突出显示这一点,而不是默默地忽略它。
您可以指定要使用的默认具体类型,但仅此而已。
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.