Protobuf 是Google的一个开源序列化库,因为使用的数据压缩算法等优化,序列化的数据较Xml更小,速度更快,因为序列化后数据是以紧凑的二进制流形式展现的,所以几乎不可直接查看。
由于Protobuf不支持.Net3.5及以下版本,所以如果要在Unity3D当中使用,则需要用到第三方的Protobuf-net库。
Protobuf-net也是开源的,项目地址如下:https://github.com/mgravell/protobuf-net
本片文章介绍最简单其最简单的用法,其他用法见后面几篇。
搜索“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); } } }}
以上程序实现了MyClass类的序列化与反序列化操作,是不是很简单!
需要注意的是序列化类的类名前需要加上“[ProtoBuf.ProtoContract]”,然后每个字段需要按照顺序在前面加上“[ProtoBuf.ProtoMember(Index)]”,这样才能使用。
后面将继续讲解protobuf-net的使用动态链接库和直接使用源码的这两种方式。
联系客服