using Google.Protobuf;
using Google.Protobuf.Reflection;
using Google.Protobuf.WellKnownTypes;
// 定义一个简单的 Protocol Buffer 消息类型
message Person {
string name = 1;
int32 id = 2;
string email = 3;
}
// 创建一个包含上述消息类型的 C# 类
public class PersonProto
{
// 定义一个方法来创建和序列化 Person 对象
public void CreateAndSerializePerson()
{
// 创建一个新的 Person 对象并设置其字段
Person person = new Person
{
Name = "John Doe",
Id = 1234,
Email = "johndoe@example.com"
};
// 序列化 Person 对象到字节数组
byte[] serializedData = person.ToByteArray();
// 反序列化字节数组回 Person 对象
Person deserializedPerson = Person.Parser.ParseFrom(serializedData);
// 输出反序列化后的对象信息
Console.WriteLine($"Name: {deserializedPerson.Name}, ID: {deserializedPerson.Id}, Email: {deserializedPerson.Email}");
}
}
Person 消息类型,它包含三个字段:name、id 和 email。PersonProto 的 C# 类,用于处理 Protocol Buffer 消息的创建和序列化。CreateAndSerializePerson 方法中,我们创建了一个新的 Person 对象,并设置了它的字段。然后,我们将这个对象序列化为字节数组。Person 对象,并输出其内容以验证操作的成功。请注意,实际使用时需要确保你已经安装了 Google.Protobuf 包,并且正确配置了你的项目以支持 Protocol Buffers。
上一篇:dictionary c#
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站