欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

C#使用protobuf-net進(jìn)行序列化的詳細(xì)操作

 更新時(shí)間:2021年11月25日 16:17:11   作者:chenzk的博客  
本文帶領(lǐng)大家學(xué)習(xí)C#中protobuf-net工具的另一種使用體驗(yàn),這個(gè)工具的使用體驗(yàn)屬于Code-First模式,先定義類(lèi)型,并使用注解進(jìn)行標(biāo)記,不需要先編寫(xiě).proto文件,感興趣的朋友跟隨小編一起看看吧

protobuf 是 google的一個(gè)開(kāi)源項(xiàng)目,可用于以下兩種用途:

(1)數(shù)據(jù)的存儲(chǔ)(序列化和反序列化),類(lèi)似于xml、json等;

(2)制作網(wǎng)絡(luò)通信協(xié)議。

  源代碼下載地址:https://github.com/mgravell/protobuf-net;

  開(kāi)源項(xiàng)目地址如下:https://code.google.com/p/protobuf-net/。

前一篇文章我們看到使用Google.Protobuf有諸多不便(參考《www.dbjr.com.cn/article/230186.htm》),這次我們來(lái)看看另一個(gè)工具的使用體驗(yàn)。

相關(guān)資料、鏈接:

  • github項(xiàng)目:https://github.com/protobuf-net/protobuf-net
  • nuget包名稱(chēng):protobuf-net、protobuf-net.BuildTools
  • 作者:Marc Gravell
  • 支持.net平臺(tái):.net5\.NETFramework4.6.1\.NETStandard2.0等
  • protobuf-net BuildTools文檔:https://protobuf-net.github.io/protobuf-net/build_tools

準(zhǔn)備工作

在C#中編寫(xiě)目標(biāo)類(lèi)型:

在類(lèi)級(jí)別增加注解[ProtoContract],在字段級(jí)別增加注解[ProtoMember(orderxxx)]

[ProtoContract]
    public class ErrorLog
    {
        [ProtoMember(1)]
        public string LogID { get; set; }
        [ProtoMember(2)]

        public string Context { get; set; }
        [ProtoMember(3)]

        public string Stack { get; set; }
    }

當(dāng)安裝了protobuf-net.BuildTools工具后,還可以在開(kāi)發(fā)時(shí)對(duì)目標(biāo)類(lèi)型(添加了[ProtoContract]注解)的定義進(jìn)行檢查,比如字段順序重復(fù)、使用的字段類(lèi)型不符合protobuf要求等。比如因疏忽設(shè)置了重復(fù)的字段順序,提示效果如下:

序列化操作

public static byte[] Serialize(ErrorLog log)
        {
            using (MemoryStream memoryStream = new MemoryStream())
            {
                ProtoBuf.Serializer.Serialize(memoryStream, log);
                return memoryStream.ToArray();
            }
        }

反序列化操作

public static ErrorLog DeSerialize(byte[] data)
        {
            using (MemoryStream ms = new MemoryStream(data))
            {
                return ProtoBuf.Serializer.Deserialize<ErrorLog>(ms);
            }
        }

總結(jié)、理解

  • 這個(gè)工具的使用體驗(yàn)屬于Code-First模式,先定義類(lèi)型,并使用注解進(jìn)行標(biāo)記,不需要先編寫(xiě).proto文件。
  • 通過(guò)類(lèi)庫(kù)提供的ProtoBuf.Serializer.Serialize()和ProtoBuf.Serializer.Deserialize()分別執(zhí)行序列化和反序列化,而不用依賴(lài)任何生成的代碼。
  • 只針對(duì).NET平臺(tái)的話(huà),不需要.proto文件就可以應(yīng)用protobuf序列化協(xié)議。如果需要跨語(yǔ)言編程,再根據(jù)C#類(lèi)型編寫(xiě).proto文件(也可以通過(guò)工具自動(dòng)生成proto文件),然后生產(chǎn)目標(biāo)語(yǔ)言的對(duì)應(yīng)類(lèi)型。
  • 借助于protobuf-net.BuildTools工具的輔助,可以及早的發(fā)現(xiàn)編碼錯(cuò)誤,一定程度上提高了開(kāi)發(fā)效率。
  • 綜上,對(duì)于.NET平臺(tái)為主的開(kāi)發(fā)者來(lái)說(shuō),使用protobuf-net相對(duì)來(lái)說(shuō)代碼可讀性更高、維護(hù)成本更小,同時(shí)也能兼顧跨語(yǔ)言開(kāi)發(fā),建議首先此方式。

到此這篇關(guān)于C#中使用protobuf-net進(jìn)行序列化的文章就介紹到這了,更多相關(guān)C# protobuf-net序列化內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論