背景:知道了Protobuf在C#控制台的用法之后兴高采烈的要弄到Unity去,然后发现Unity5还是只支持到.net 3.5,东找找西找找,有人说用Protobuf-net,有人说也可以用Protobuf-csharp-port,选了Protobuf-net来试试
1.VS 2017 创建.net3.5的dll工程, Nuget 打包protobuf-net成dll放到Unity工程的Plugins目录
2.创建Protobuf
//
[ProtoContract]
class Person {
[ProtoMember(1)]
public int Id {get;set;}
[ProtoMember(2)]
public string Name {get;set;}
[ProtoMember(3)]
public Address Address {get;set;}
}
[ProtoContract]
class Address {
[ProtoMember(1)]
public string Line1 {get;set;}
[ProtoMember(2)]
public string Line2 {get;set;}
}
3.序列化Protobuf对象
// 利用FileStream作为序列化的载体,会创建本地文件
using (var file = File.Create("person.bin")) {
Serializer.Serialize(file, person);
}
// 利用MemoryStream作为序列化的载体,转化为byte数组
using (MemoryStream stream = new MemoryStream()){
ProtoBuf.Serializer.Serialize(stream,my);
byte[] result = new byte[stream.Length];
stream.Position = 0;
stream.Read(result,0,result.Length);
stream.Close();
return result;
}
4.反序列化Protobuf对象
// 使用FileStream作为反序列化的载体,转换为Protobuf对象
using (var file = File.OpenRead("person.bin")) {
newPerson = Serializer.Deserialize<Person>(file);
}
// 使用MemoryStream作为反序列化载体,转化为Protobuf对象
using(MemoryStream stream = new MemoryStream()){
stream.Write(info,0,info.Length);
stream.Position = 0;
Hello hello =ProtoBuf.Serializer.Deserialize<Hello>(stream);
stream.Close();
}