网站建设shebei谷歌 翻墙入口
Protobuf 学习简记(三)Unity C#中的序列化与反序列化
- 对文本的序列化与反序列化
- 内存二进制流的序列化与反序列化
- 方法一
- 方法二
- 参考链接
对文本的序列化与反序列化
private void Text()
{TestMsg1 myTestMsg = new TestMsg1();myTestMsg.TestInt32 = 1;myTestMsg.ArrString.Add("wy");myTestMsg.ArrString.Add("pnb");myTestMsg.ArrString.Add("lzq");myTestMsg.Map1.Add(1, "ywj");myTestMsg.Map1.Add(2, "zzs");//序列化string path = Application.persistentDataPath + "/testMsg.msg";using (FileStream fs = new FileStream(path, FileMode.OpenOrCreate)){myTestMsg.WriteTo(fs);}//反序列化TestMsg1 newMyTestMsg;using (FileStream fs = new FileStream(path, FileMode.Open)){newMyTestMsg = TestMsg1.Parser.ParseFrom(fs);}Debug.Log(newMyTestMsg.TestInt32);Debug.Log(newMyTestMsg.ArrString);Debug.Log(newMyTestMsg.ArrString.Count);Debug.Log(newMyTestMsg.Map1[1]);Debug.Log(newMyTestMsg.Map1[2]);
}
内存二进制流的序列化与反序列化
方法一
private void Start2()
{TestMsg1 myTestMsg = new TestMsg1{TestInt32 = 1};myTestMsg.ArrString.Add("wy");myTestMsg.ArrString.Add("pnb");myTestMsg.ArrString.Add("lzq");myTestMsg.Map1.Add(1, "ywj");myTestMsg.Map1.Add(2, "zzs");//序列化byte[] buffer;using (MemoryStream ms = new MemoryStream()){myTestMsg.WriteTo(ms);buffer = ms.ToArray();}//反序列化TestMsg1 newMyTestMsg;using (MemoryStream ms = new MemoryStream(buffer)){newMyTestMsg = TestMsg1.Parser.ParseFrom(ms);}Debug.Log(newMyTestMsg.TestInt32);Debug.Log(newMyTestMsg.ArrString);Debug.Log(newMyTestMsg.ArrString.Count);Debug.Log(newMyTestMsg.Map1[1]);Debug.Log(newMyTestMsg.Map1[2]);
}
方法二
private void Start3()
{TestMsg1 myTestMsg = new TestMsg1{TestInt32 = 1};myTestMsg.ArrString.Add("wy");myTestMsg.ArrString.Add("pnb");myTestMsg.ArrString.Add("lzq");myTestMsg.Map1.Add(1, "ywj");myTestMsg.Map1.Add(2, "zzs");byte[] buffer = myTestMsg.ToByteArray();//序列化TestMsg1 newMyTestMsg = TestMsg1.Parser.ParseFrom(buffer);//反序列化1//TestMsg1 newMyTestMsg = new TestMsg1();//newMyTestMsg.MergeFrom(buffer);//反序列化2Debug.Log(newMyTestMsg.TestInt32);Debug.Log(newMyTestMsg.ArrString);Debug.Log(newMyTestMsg.ArrString.Count);Debug.Log(newMyTestMsg.Map1[1]);Debug.Log(newMyTestMsg.Map1[2]);
}
反序列化1与反序列化2都可以正常使用。
参考链接
- https://blog.csdn.net/zzzsss123333/article/details/125505066
- https://blog.csdn.net/u011723630/article/details/127464374
另外有《unity中使用protobuf-net库》的文章示例:
- https://www.jb51.cc/unity/3755981.html
- https://stackoverflow.com/questions/57714689/protobuf-net-il2cpp-system-reflection-emit-is-not-supported/57721927#57721927