How is protobuf used in C#?

In C#, using protobuf mainly involves two steps: defining message format and serializing/deserializing messages.

1. Define message format: Define message format using Protobuf language, usually done in a .proto file. For example, defining a simple message format as follows:

syntax = "proto3";

message Person {
  string name = 1;
  int32 id = 2;
}

2. Message Serialization/Deserialization: In C#, use the protobuf library to perform message serialization and deserialization. First, install the protobuf library by installing the Google.Protobuf library through NuGet package manager.

using Google.Protobuf;
using System.IO;

// 序列化消息
Person person = new Person
{
    Name = "Alice",
    Id = 123
};

using (MemoryStream stream = new MemoryStream())
{
    person.WriteTo(stream);
    byte[] bytes = stream.ToArray();
}

// 反序列化消息
using (MemoryStream stream = new MemoryStream(bytes))
{
    Person newPerson = Person.Parser.ParseFrom(stream);
    Console.WriteLine($"Name: {newPerson.Name}, Id: {newPerson.Id}");
}

By following the above steps, you can use protobuf in C# to achieve message serialization and deserialization.

bannerAds