将 List<> 转换为流时出现 protobuf 错误:没有类型的序列化器

protobuf Error when converting List<> to stream: No serializer for type

我正在尝试做一些我认为应该很简单的事情:将 List<object> 转换为 stream

using ProtoBuf;
using System.Collections.Generic;
using System.IO;

namespace ConsoleApp1
{

    class MyObject
    {
        public string Prop1 { get; set; }
        public string Prop2 { get; set; }
        public string Prop3 { get; set; }
    }


    class Program
    {
        static void Main(string[] args)
        {
            List<MyObject> myObjects = new();
            myObjects.Add(new() { Prop1 = "foo1", Prop2 = "bar1", Prop3 = "something1" });
            myObjects.Add(new() { Prop1 = "foo2", Prop2 = "bar2", Prop3 = "something2" });
            myObjects.Add(new() { Prop1 = "foo3", Prop2 = "bar3", Prop3 = "something3" });

            using var stream = new MemoryStream();

            Serializer.Serialize(stream, myObjects); // Error is here

            byte[] bytes = stream.ToArray();
        }
    }
}

这是错误:

System.InvalidOperationException HResult=0x80131509 Message=No serializer for type ConsoleApp1.MyObject is available for model (default) Source=protobuf-net.Core

您必须像这样将 ProtoContract 添加到您的 class 中:

[ProtoContract]
class MyObject
{
    [ProtoMember(1)]
    public string Prop1 { get; set; }
    [ProtoMember(2)]
    public string Prop2 { get; set; }
    [ProtoMember(3)]
    public string Prop3 { get; set; }
}

https://github.com/protobuf-net/protobuf-net/blob/main/README.md