在c#中使用Protobuf

安装包

Google.Protobuf
Google.Protobuf.Tools

Google.Protobuf.Tools中存在protoc.exe可以用来编译.proto文件

编写 Person.proto 文件

syntax = "proto3";
message Person {
string name = 1;
int32 id = 2;
string email = 3;
}

使用protoc.exe编译

protoc.exe --csharp_out=. *.proto

得到 Person.cs文件,将其引入到项目中

在c#中使用

using Google.Protobuf;
// 序列化
Person person = new Person { Name = "Alice", Id = 123, Email = "alice@example.com" };
byte[] data = person.ToByteArray();
Console.WriteLine($"Length:{data.Length}");
Console.WriteLine($"{Convert.ToBase64String(data)}");
// 反序列化
Person newPerson = Person.Parser.ParseFrom(data);
Console.WriteLine($"Name:{newPerson.Name}");
Console.Read();
posted @   trykle  阅读(216)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示