日韩黑丝制服一区视频播放|日韩欧美人妻丝袜视频在线观看|九九影院一级蜜桃|亚洲中文在线导航|青草草视频在线观看|婷婷五月色伊人网站|日本一区二区在线|国产AV一二三四区毛片|正在播放久草视频|亚洲色图精品一区

分享

[Unity3D]簡單使用Protobuf

 kiki的號 2017-07-22

Protobuf 是Google的一個開源序列化庫,因為使用的數據壓縮算法等優(yōu)化,序列化的數據較Xml更小,速度更快,因為序列化后數據是以緊湊的二進制流形式展現的,所以幾乎不可直接查看。

由于Protobuf不支持.Net3.5及以下版本,所以如果要在Unity3D當中使用,則需要用到第三方的Protobuf-net庫。

Protobuf-net也是開源的,項目地址如下:https://github.com/mgravell/protobuf-net

本片文章介紹最簡單其最簡單的用法,其他用法見后面幾篇。

  1. 創(chuàng)建一個C#的控制臺程序
  2. 點擊項目右鍵打開“管理NuGet程序包”。
  3. 搜索“Protobuf-net”,并安裝,如下:

    這里寫圖片描述

  4. 編輯測試代碼如下:

using System.Collections.Generic;
using System.IO;

namespace ProtoTest_1
{
    [ProtoBuf.ProtoContract]
    class MyClass
    {
        [ProtoBuf.ProtoMember(1)]
        public int _nNumber;
        [ProtoBuf.ProtoMember(2)]
        public string _strName;
        [ProtoBuf.ProtoMember(3)]
        public List<string> _lstInfo;
        [ProtoBuf.ProtoMember(4)]
        public Dictionary<int, string> _dictInfo;
    }

    class Program
    {
        static void Main(string[] args)
        {
            //測試用數據
            MyClass my = new MyClass();
            my._nNumber = 0;
            my._strName = "test";
            my._lstInfo = new List<string>();
            my._lstInfo.Add("a");
            my._lstInfo.Add("b");
            my._lstInfo.Add("c");
            my._dictInfo = new Dictionary<int, string>();
            my._dictInfo.Add(1, "a");
            my._dictInfo.Add(2, "b");
            my._dictInfo.Add(3, "c");

            using (FileStream stream = File.OpenWrite("test.dat"))
            {
                //序列化后的數據存入文件
                ProtoBuf.Serializer.Serialize<MyClass>(stream, my);
            }

            MyClass my2 = null;
            using (FileStream stream = File.OpenRead("test.dat"))
            {
                //從文件中讀取數據并反序列化
                my2 = ProtoBuf.Serializer.Deserialize<MyClass>(stream);
            }
        }
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51

以上程序實現了MyClass類的序列化與反序列化操作,是不是很簡單!

需要注意的是序列化類的類名前需要加上“[ProtoBuf.ProtoContract]”,然后每個字段需要按照順序在前面加上“[ProtoBuf.ProtoMember(Index)]”,這樣才能使用。
后面將繼續(xù)講解protobuf-net的使用動態(tài)鏈接庫和直接使用源碼的這兩種方式。

這里寫圖片描述

    本站是提供個人知識管理的網絡存儲空間,所有內容均由用戶發(fā)布,不代表本站觀點。請注意甄別內容中的聯(lián)系方式、誘導購買等信息,謹防詐騙。如發(fā)現有害或侵權內容,請點擊一鍵舉報。
    轉藏 分享 獻花(0

    0條評論

    發(fā)表

    請遵守用戶 評論公約

    類似文章 更多