C# .net protocol buffers - protobuf-net support for serializing dictionary of object values?

跟風遠走 提交于 2019-12-12 09:36:38

问题


i'm new to protocol buffers and I am using protobuf-net for VS2010. from what i'm reading here Dictionary in protocol buffers, it doesn't seem that protobuf can serialize a dictionary with object types as values. but here on his site i read this:

Notes on types

supported:

custom classes that: are marked as data-contract have a parameterless constructor for Silverlight: are public many common primitives etc single dimension arrays: T[] List / IList Dictionary / IDictionary any type which implements IEnumerable and has an Add(T) method The code assumes that types will be mutable around the elected members. Accordingly, custom structs are not supported, since they should be immutable.

which seems like it is supported.

I can successfully compile a List of objects like so:

message ValuesObject {
    optional int32 SomeVal = 1;
    repeated SomeClass ListOfSomeClassTypes = 2;
}

This works fine for a List<SomeClass>. Why cannot I serialize using protobuf-net a Dictionary<int, SomeClass>? What would the message look like to serialize a Dictionary<int, SomeClass>?


回答1:


A Dictionary<int,SomeClass> is perfectly serailizable with protobuf-net. Protobuf-net works simplest when working code-first, so: *just have a Dictionary<int,SomeClass> in your model. You are not required to use a .proto at all - that is provided mainly for cross-platform purposes. The .proto specification has no concept of a dictionary, but if you are required to use a .proto schema, then this is serialized as:

message KeyValuePairInt32SomeClass {
    required int32 Key = 1;
    required SomeClass Value = 2;
}

with the dictionary as

repeated KeyValuePairInt32SomeClass YourDictionary = [n]; 


来源:https://stackoverflow.com/questions/10890922/c-sharp-net-protocol-buffers-protobuf-net-support-for-serializing-dictionary

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!