ProtoBuf使用

ProtoBuf也是一種序列化的方法


什么是 Google Protocol Buffer? 假如您在網(wǎng)上搜索,應(yīng)該會(huì)得到類似這樣的文字介紹:

Google Protocol Buffer( 簡(jiǎn)稱 Protobuf) 是 Google 公司內(nèi)部的混合語(yǔ)言數(shù)據(jù)標(biāo)準(zhǔn),目前已經(jīng)正在使用的有超過(guò) 48,162 種報(bào)文格式定義和超過(guò) 12,183 個(gè) .proto 文件。他們用于 RPC 系統(tǒng)和持續(xù)數(shù)據(jù)存儲(chǔ)系統(tǒng)。

Protocol Buffers 是一種輕便高效的結(jié)構(gòu)化數(shù)據(jù)存儲(chǔ)格式,可以用于結(jié)構(gòu)化數(shù)據(jù)串行化,或者說(shuō)序列化。它很適合做數(shù)據(jù)存儲(chǔ)或 RPC 數(shù)據(jù)交換格式。可用于通訊協(xié)議、數(shù)據(jù)存儲(chǔ)等領(lǐng)域的語(yǔ)言無(wú)關(guān)、平臺(tái)無(wú)關(guān)、可擴(kuò)展的序列化結(jié)構(gòu)數(shù)據(jù)格式可以直接在官網(wǎng)下載Dll文件

導(dǎo)入到工程中就可以用了

ProTobuf這個(gè)命名空間是常用的

在需要序列花的類簽名上面加上[ProtoContract]

在類的字段簽名上加[ProtoMeber(i)]每個(gè)都加括號(hào)的數(shù)字增加

需要序列化的類

//需要被序列化的類都要加上這個(gè)可序列化特性

? ? [ProtoContract]

? ? class ProtoBuf {

? ? ? ? //成員也要加這個(gè)

? ? ? ? [ProtoMember(1)]

? ? ? ? public int MyProperty { get; set; }

? ? ? ? [ProtoMember(2)]

? ? ? ? public int Age { get; set; }

? ? }

//序列化對(duì)象



static byte[] GetVs(object value) {

? ? ? ? ? ? byte[] buffer = null;

? ? ? ? ? ? //創(chuàng)建內(nèi)存流

? ? ? ? ? ? using (MemoryStream ms=new MemoryStream()) {

? ? ? ? ? ? ? ? if (value != null) {

? ? ? ? ? ? ? ? ? ? //序列化對(duì)象

? ? ? ? ? ? ? ? ? ? RuntimeTypeModel.Default.Serialize(ms, value);

? ? ? ? ? ? ? ? ? ? //重置當(dāng)前流的位置

? ? ? ? ? ? ? ? ? ? ms.Position = 0;

? ? ? ? ? ? ? ? ? ? //從流中讀取字節(jié)寫(xiě)到緩沖區(qū)必須把緩沖區(qū)實(shí)例化出來(lái)

? ? ? ? ? ? ? ? ? ? buffer = new byte[ms.Length];

? ? ? ? ? ? ? ? ? ? //從流中讀取數(shù)據(jù)寫(xiě)到緩沖區(qū)

? ? ? ? ? ? ? ? ? ? ms.Read(buffer, 0, (int)ms.Length);

? ? ? ? ? ? ? ? }

? ? ? ? ? ? }

? ? ? ? ? ? return buffer;

? ? ? ? }

反序列化對(duì)象


//通過(guò)Protobuf的泛型反序列化 static object DProtobuffer(byte[] data) {?

?object value = null;?

//創(chuàng)建內(nèi)存流對(duì)象并把字節(jié)數(shù)組寫(xiě)入流中

?using (MemoryStream ms=new MemoryStream(data)) {

?//使用protobuf的泛型方法反序列化對(duì)象參數(shù)是流返回值是object?

?value = Serializer.Deserialize(ms);

? ? ? ? ? ? }

? ? ? ? ? ? return value;

? ? ? ? }

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容