Protobuf-net仅使用getter序列化属性失败-无法对属性应用更改

本文关键字:属性 应用 失败 getter 序列化 Protobuf-net | 更新日期: 2023-09-27 18:15:14

我正在使用protobuf-net序列化一个对象,我得到异常:

不能应用更改属性TestProject.TestMessage.ClientId

与加亮:

at ProtoBuf.Serializers.PropertyDecorator.SanityCheck(TypeModel model, PropertyInfo property, IProtoSerializer tail, Boolean& writeValue, Boolean nonPublic, Boolean allowInternal)
at ProtoBuf.Serializers.PropertyDecorator..ctor(TypeModel model, Type forType, PropertyInfo property, IProtoSerializer tail)
at ProtoBuf.Meta.ValueMember.BuildSerializer()
at ProtoBuf.Meta.ValueMember.get_Serializer()
at ProtoBuf.Meta.MetaType.BuildSerializer()
at ProtoBuf.Meta.MetaType.get_Serializer()
at ProtoBuf.Meta.RuntimeTypeModel.Serialize(Int32 key, Object value, ProtoWriter dest)
at ProtoBuf.Meta.TypeModel.SerializeCore(ProtoWriter writer, Object value)
at ProtoBuf.Meta.TypeModel.Serialize(Stream dest, Object value, SerializationContext context)
at ProtoBuf.Meta.TypeModel.Serialize(Stream dest, Object value)
at ProtoBuf.Serializer.Serialize[T](Stream destination, T instance)

我的班级如下:

[DataContract]
public class TestMessage
{
    private int clientId;
    [DataMember(Order = 1)]
    public int ClientId
    {
        get { return clientId; }
    }
    private string name;
    [DataMember(Order = 2)]
    public string Name
    {
        get { return name; }
    }
    public TestMessage(int clientId,
                                string name)
    {
        this.clientId = clientId;
        this.name =name;
    }
}

Protobuf-net仅使用getter序列化属性失败-无法对属性应用更改

是的,这是正确的:protobuf-net不能成功往返get-only属性,例如您的ClientId,因此将抛出一个异常,试图构建一个显式要求序列化此类属性的合约。

它并不是唯一有这种限制的。我注意到你正在用数据契约属性标记你的类型。如果我尝试用DataContractSerializer序列化它的一个实例,它会失败,并产生一个等效的异常:

System.Runtime.Serialization.InvalidDataContractException was caught
  Message="No set method for property 'ClientId' in type 'Question40276317.V1.TestMessage'."
  Source="System.Runtime.Serialization"

如果你只是想跳过get-only属性,那么用[IgnoreDataMember]标记它们。如果您想成功地序列化和反序列化它们,您有以下选项:

首先,protobuf-net需要能够构造你的对象。与Json。NET不会调用参数化构造函数,所以最简单的方法是添加无参数构造函数。只要它存在,它就可以是私有的或受保护的(在完整框架上)。或者,您可以设置[ProtoContract(SkipConstructor = true)],但是这并不适用于所有框架或部分信任的情况。

接下来,您需要以某种方式使属性可设置。一个解决方案是添加私有设置:
[DataContract]
public class TestMessage
{
    private int clientId;
    [DataMember(Order = 1)]
    public int ClientId
    {
        get { return clientId; }
        private set { clientId = value; }
    }
    private string name;
    [DataMember(Order = 2)]
    public string Name
    {
        get { return name; }
        private set { name = value; }
    }
    protected TestMessage() { }
    public TestMessage(int clientId, string name)
    {
        this.clientId = clientId;
        this.name = name;
    }
}

另一种方法是用数据契约属性标记底层字段而不是属性:

[DataContract]
public class TestMessage
{
    [DataMember(Name = "ClientId", Order = 1)]
    private int clientId;
    public int ClientId
    {
        get { return clientId; }
    }
    [DataMember(Name = "Name", Order = 2)]
    private string name;
    public string Name
    {
        get { return name; }
    }
    protected TestMessage() { }
    public TestMessage(int clientId, string name)
    {
        this.clientId = clientId;
        this.name = name;
    }
}

或者,如果您真的希望clientIdname的值在构造之后是不可变的,那么您将需要一个序列化代理,如下所示:

public class TestMessage
{
    private readonly int clientId;
    public int ClientId
    {
        get { return clientId; }
    }
    private readonly string name;
    public string Name
    {
        get { return name; }
    }
    public TestMessage(int clientId, string name)
    {
        this.clientId = clientId;
        this.name = name;
    }
}
[DataContract]
internal class TestMessageSurrogate
{
    public static implicit operator TestMessageSurrogate(TestMessage message)
    {
        if (message == null)
            return null;
        return new TestMessageSurrogate { ClientId = message.ClientId, Name = message.Name };
    }
    public static implicit operator TestMessage(TestMessageSurrogate message)
    {
        if (message == null)
            return null;
        return new TestMessage(message.ClientId, message.Name);
    }
    [DataMember(Order = 1)]
    public int ClientId { get; set; }
    [DataMember(Order = 2)]
    public string Name { get; set; }
}

那么,在序列化之前,执行:

ProtoBuf.Meta.RuntimeTypeModel.Default.Add(typeof(TestMessage), true).SetSurrogate(typeof(TestMessageSurrogate));

通过使用代理,您还可以避免使用任何无参数的构造函数。