Protobuf 是Google的一個開源序列化庫,因為使用的數據壓縮算法等優(yōu)化,序列化的數據較Xml更小,速度更快,因為序列化后數據是以緊湊的二進制流形式展現的,所以幾乎不可直接查看。
由于Protobuf不支持.Net3.5及以下版本,所以如果要在Unity3D當中使用,則需要用到第三方的Protobuf-net庫。
Protobuf-net也是開源的,項目地址如下:https://github.com/mgravell/protobuf-net
本片文章介紹最簡單其最簡單的用法,其他用法見后面幾篇。
- 創(chuàng)建一個C#的控制臺程序
- 點擊項目右鍵打開“管理NuGet程序包”。
搜索“Protobuf-net”,并安裝,如下:

編輯測試代碼如下:
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)鏈接庫和直接使用源碼的這兩種方式。

|