在c#中使用Protobuf

trykle / 2024-11-11 / 原文

安装包

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();