Below you will find pages that utilize the taxonomy term “Protobuf-Net”
Posts
protobuf-net - Serialize/DeSerialize data
protobuf-net 預設只支援序列化至 stream,或是自 stream 姐序列化回物件。使用上就是透過 Serializer.Serialize 帶入 stream 與物件,帶入的物件就會被序列化至 stream,呼叫 Serializer.Deserialize,帶入 stream,泛型型態設定為指定的類別型態,就可以自 stream 解序列化回指定型態的物件。
private static void SerializeToStream<T>(T obj, Stream stream) { Serializer.Serialize(stream, obj); } private static T DeSerializeFromStream<T>(Stream stream) { return Serializer.Deserialize<T>(stream); } 如果要序列化為字串,可以將物件先序列化到 stream,然後將他轉成 Base 64 的字串。解序列化反向操作即可。
private static string SerializeToText<T>(T obj) { using (var ms = new MemoryStream(1024)) { SerializeToStream(obj, ms); return Convert.ToBase64String(ms.ToArray()); } } private static T DeSerializeFromText<T>(string text) { var buffer = Convert.FromBase64String(text); using (var ms = new MemoryStream(buffer)) { return DeSerializeFromStream<T>(ms); } } 序列化到檔案的話,就是開啟檔案串流,將物件序列化到檔案串流即可。解序列化一樣反向操作。
read morePosts
protobuf-net - Decorate class
protobuf-net 要設定類別怎樣被序列化與解序列化有三種方式‧
像是使用 protobuf-net 提供的 Attribute,類別上用 ProtoContractAttribute、Property 上用 ProtoMemberAttribute‧
[ProtoContract] class Person { [ProtoMember(1)] public int Id {get;set;} [ProtoMember(2)] public string Name {get;set:} [ProtoMember(3)] public Address Address {get;set;} } [ProtoContract] class Address { [ProtoMember(1)] public string Line1 {get;set;} [ProtoMember(2)] public string Line2 {get;set;} } 如果有繼層的類別可以透過 ProtoIncludeAttribute 設定。
[ProtoContract] [ProtoInclude(10, typeof(Male))] [ProtoInclude(11, typeof(Female))] class Person { [ProtoMember(1)] public string Name { get; set; } } [ProtoContract] class Male : Person { } [ProtoContract] class Female : Person { } ProtoContractAttribute 這邊還有提供些設定,像是 SkipConstructor 可以讓類別解序列化時不需要有建構子、ImplicitFields 可以設定全部的欄位或是屬性都序列化解序列化。
read morePosts
protobuf-net - Getting Started
使用 protobuf-net,首先要參照 protobuf-net library,接著設定要用來做序列化或解序列化用的類別,設定完後就可以用 protobuf-net 來序列化或解序列化。
protobuf-net library 透過 NuGet 引用即可。
接著準備用來做序列化或解序列化用的類別,類別可透過 Attribute 的方式決定怎樣序列化或解序列化。
[ProtoContract] class Person { [ProtoMember(1)] public int Id {get;set;} [ProtoMember(2)] public string Name {get;set:} [ProtoMember(3)] public Address Address {get;set;} } [ProtoContract] class Address { [ProtoMember(1)] public string Line1 {get;set;} [ProtoMember(2)] public string Line2 {get;set;} } 序列化時只要調用 Serializer.Serialize 帶入 Stream 與要序列化的物件。
var person = new Person { Id = 12345, Name = "Fred", Address = new Address { Line1 = "Flat 1", Line2 = "The Meadows" } }; using (var file = File.
read more