使用 protobuf 中的属性指定所有子封闭泛型类型

Specify all child closed generic types using attributes in protobuf

我使用 protobuf-net 2.4 并具有下一个 class 层次结构:

[ProtoContract]
public class BaseStub
{
    [ProtoMember(1)]
    public string Text { get; set; }
}

[ProtoContract]
public class GenericStub<T1> : BaseStub
{
    [ProtoMember(1)]
    public T1 Value1 { get; set; }
}

并且我知道将用作 T1 的所有可能类型(例如只有双精度)。我可以在运行时注册这种类型,像这样:

var model = RuntimeTypeModel.Default;
var baseType = model.Add(typeof(BaseStub), true);
model.Add(typeof(GenericStub<double>), true);
baseType.AddSubType(100, typeof(GenericStub<double>)

但是我可以使用属性做同样的事情吗?我尝试使用 ProtoInclude,但收到空引用错误。

[ProtoContract]
[ProtoInclude(100, typeof(GenericStub<double>))]
public class BaseStub {...}

应该可以,例如 - 这对我有用:

BaseStub obj = new GenericStub<double> { Text = "abc", Value1 = 123.45 };
var clone = (GenericStub<double>)Serializer.DeepClone(obj);
Console.WriteLine($"{clone.Text}, {clone.Value1}");

如果您看到 NRE - 完整的重现会有所帮助。