将 ProtoInclude 绑定到相应的 RuntimeTypeModel 绑定不起作用

Binding a ProtoInclude to the corresponding RuntimeTypeModel binding doesn't work

我目前正在试用 protobuf-net,但在序列化以下 class 结构时遇到问题:

[ProtoContract]
public abstract class WorkerResponseBase
{
    [ProtoMember(1)]
    public WorkerErrorMessage ErrorMessage { get; set; }

    [ProtoMember(2)]
    public bool IsSuccess { get; set; }

    [ProtoMember(3)]
    public bool IsError { get; set; }

    protected WorkerResponseBase()
    {
    }

    protected WorkerResponseBase(bool isSuccess, [CanBeNull] string errorMessage)
    {
        IsSuccess = isSuccess;
        IsError = !isSuccess;
        ErrorMessage = new WorkerErrorMessage(errorMessage);
    }
}

[ProtoContract()]
public class WorkerResponse<TPayload> : WorkerResponseBase
{
    [ProtoMember(4)]
    public TPayload PayloadOrNull { get; private set; }

    ....
}

当我第一次尝试使用具体的 class 时,例如WorkerResponse<LoginResult>,我只能序列化 PayloadOrNull。

好的,我 google 了解了如何完成这项工作。我找到了这个答案:ProtoBuf-Net ProtoInclude Generic Type Subclass

有人提到,[ProtoInclude] 是必需的。

因此,为了对此进行测试,我试图用 [ProtoInclude(100, typeof(WorkerResponse<LoginResult>))] 装饰 WorkerResponseBase。宾果游戏,序列化完美。

现在,正如您可能想象的那样,这是一个非常通用的响应容器,所以我不想在基础 class 中定义所有可能的 TPayload,所以有点在我发现的链接评论的更下方,我也应该能够动态地执行此操作,并最终通过反射。

所以出于测试目的,我做了以下而不是 [ProtoInclude]:

RuntimeTypeModel.Default.Add(typeof(WorkerResponseBase), false)
    .AddSubType(100, typeof(WorkerResponse<LoginResult>));

但是,当我 运行 这个时,根本没有序列化工作,甚至连 PayloadOrNull.

的序列化都没有

那么,我做错了什么?

代码中的 false(到 Add)基本上是说 "and I'm going to control everything myself, don't process the properties and their attributes - I'll tell you explicitly"。由于您 没有 这样做,您可能想要通过 true。在pending V3 API中,这是一个可选参数,默认为true.