编程语言
首页 > 编程语言> > c# – protobuf-net能处理自动只读属性吗?

c# – protobuf-net能处理自动只读属性吗?

作者:互联网

protobuf-net能否处理新的自动只读属性,即使用单个get和no私有集定义的自动属性?

public class WithReadonlyProperty {
    public int ReadonlyProperty { get; }
    public WithReadonlyProperty(int val) {
        ReadonlyProperty = val;
    }
}

当我这样做

RuntimeTypeModel
    .Default
    .Add(typeof (WithReadonlyProperty), false)
        .Add(nameof(WithReadonlyProperty.ReadonlyProperty));
var test = new WithReadonlyProperty(12345);
using (var output = File.Create(@"c:\temp\_readonly.bin")) {
    try {
        Serializer.Serialize(output, test);
    } catch (Exception e) {
        Console.WriteLine(e);
    }
}

我得到这个例外:

System.InvalidOperationException: Cannot apply changes to property WithReadonlyProperty.ReadonlyProperty
   at ProtoBuf.Serializers.PropertyDecorator.SanityCheck(TypeModel model, PropertyInfo property, IProtoSerializer tail, Boolean& writeValue, Boolean nonPublic, Boolean allowInternal) in c:\Dev\protobuf-net\protobuf-net\Serializers\PropertyDecorator.cs:line 46
   at ProtoBuf.Serializers.PropertyDecorator..ctor(TypeModel model, Type forType, PropertyInfo property, IProtoSerializer tail) in c:\Dev\protobuf-net\protobuf-net\Serializers\PropertyDecorator.cs:line 32
   at ProtoBuf.Meta.ValueMember.BuildSerializer() in c:\Dev\protobuf-net\protobuf-net\Meta\ValueMember.cs:line 375
   at ProtoBuf.Meta.MetaType.BuildSerializer() in c:\Dev\protobuf-net\protobuf-net\Meta\MetaType.cs:line 408
   at ProtoBuf.Meta.MetaType.get_Serializer() in c:\Dev\protobuf-net\protobuf-net\Meta\MetaType.cs:line 384
   at ProtoBuf.Meta.RuntimeTypeModel.Serialize(Int32 key, Object value, ProtoWriter dest) in c:\Dev\protobuf-net\protobuf-net\Meta\RuntimeTypeModel.cs:line 752
   at ProtoBuf.Meta.TypeModel.SerializeCore(ProtoWriter writer, Object value) in c:\Dev\protobuf-net\protobuf-net\Meta\TypeModel.cs:line 186
   at ProtoBuf.Meta.TypeModel.Serialize(Stream dest, Object value, SerializationContext context) in c:\Dev\protobuf-net\protobuf-net\Meta\TypeModel.cs:line 217
   at ProtoBuf.Serializer.Serialize[T](Stream destination, T instance) in c:\Dev\protobuf-net\protobuf-net\Serializer.cs:line 86
    ...

是否可以配置protobuf-net以使用公共构造函数?是否有其他方法可以做到这一点?如果可能的话,我想避免使用属性来装饰WithReadonlyProperty类.

解决方法:

Protobuf可以使用私有构造函数,所以也许你可以为protobuf使用私有构造函数?

标签:c,protobuf-net
来源: https://codeday.me/bug/20190711/1433879.html