C#protobufによるオブジェクトのシーケンス化と逆シーケンス化

6999 ワード

protobufはgoogleのオープンソースプロジェクトで、以下の2つの用途に使用できます.
(1)xml、jsonなどに類似したデータの格納(シーケンス化と逆シーケンス化).
(2)ネットワーク通信プロトコルを作成する.
ソースコードのダウンロードアドレス:https://github.com/mgravell/protobuf-net;
オープンソースプロジェクトのアドレスは次のとおりです.https://code.google.com/p/protobuf-net/.
protobufツールクラスDataUtils.csコードは以下の通りです.
nugetパッケージ
Install-Package ServiceStack.ProtoBuf -Version 5.1.0
using System; using System.IO; using ProtoBuf; namespace nugetdll { public class DataUtils { public static byte[] ObjectToBytes(T instance) { try { byte[] array; if (instance == null) { array = new byte[0]; } else { MemoryStream memoryStream = new MemoryStream(); Serializer.Serialize(memoryStream, instance); array = new byte[memoryStream.Length]; memoryStream.Position = 0L; memoryStream.Read(array, 0, array.Length); memoryStream.Dispose(); } return array; } catch (Exception ex) { return new byte[0]; } } public static T BytesToObject(byte[] bytesData, int offset, int length) { if (bytesData.Length == 0) { return default(T); } try { MemoryStream memoryStream = new MemoryStream(); memoryStream.Write(bytesData, 0, bytesData.Length); memoryStream.Position = 0L; T result = Serializer.Deserialize(memoryStream); memoryStream.Dispose(); return result; } catch (Exception ex) { return default(T); } } } [ProtoContract] public class Test { [ProtoMember(1)] public string S { get; set; } [ProtoMember(2)] public string Type { get; set; } [ProtoMember(3)] public int I { get; set; } /// /// , No parameterless constructor found for x ! /// public Test() { } public static Test Data => new Test { I = 222, S = "xxxxxx", Type = " " }; } }
 
転載先:https://www.cnblogs.com/liuxiaoji/p/9517635.html