- 简介
- 实例
从网上参考了一个例子 http://blog.csdn.net/ddxkjddx/article/details/7239798
//----------------实体类----------------------
using UnityEngine; using System.Collections; using ProtoBuf; using System; using System.Collections.Generic; [ProtoContract] public class Test { [ProtoMember(1)] public int Id { get; set; } [ProtoMember(2)] public List<String> data { get; set; } public override string ToString() { String str = Id+":"; foreach (String d in data) { str += d + ","; } return str; } }
//-----------测试类---------------------------
using UnityEngine; using System.Collections; using System.Collections.Generic; using System.IO; using ProtoBuf; using System; public class ProtobufNet : MonoBehaviour { private const String PATH = "c://data.bin"; void Start () { //生成数据 List<Test> testData = new List<Test>(); for (int i = 0; i < 100; i++) { testData.Add(new Test() { Id = i, data = new List<string>(new string[]{"1","2","3"}) }); } //将数据序列化后存入本地文件 using(Stream file = File.Create(PATH)) { Serializer.Serialize<List<Test>>(file, testData); file.Close(); } //将数据从文件中读取出来,反序列化 List<Test> fileData; using (Stream file = File.OpenRead(PATH)) { fileData = Serializer.Deserialize<List<Test>>(file); } //打印数据 foreach (Test data in fileData) { Debug.Log(data); } } }
- 总结
Protobuf-net 利用Attributes来实现序列化字段,对程序员的负担减轻,代码侵入性也降低。接下来,我将会写一个简单的Unity c/s demo,其中的通信编码就是用到Protobuf,
到时再与大家分享。