Google Protocol Buffers - 序列化为字节数组

Google Protocol Buffers - serialize to byte array

我正在学习使用 Google Protocol Buffers for C# 的教程。我没有看到将对象转换为字节数组的示例 - 有人知道该怎么做吗?我已经使用 protoc 编译器自动生成了一个 FilePath 类 并且到目前为止:

FilePath fp = new FilePath
{
    Path = "TestPath",
    RealTimeMultiple = 5.0f
};

所以,我需要知道如何在不使用 BinaryFormatter 的情况下正确序列化 fp 对象。

假设您正在使用 Google.Protobuf nuget 包,您可以只使用:

using Google.Protobuf;

...

byte[] bytes = fp.ToByteArray();

您需要 Google.Protobufusing 指令才能使 IMessage.ToByteArray 扩展方法可用 - 这可能是您之前所缺少的。