c# - protobuf-net 可以处理自动只读属性吗?

标签 c# protobuf-net

<分区>

protobuf-net 能否处理新的自动只读属性,即使用单个 get 定义的自动属性,而不使用 private set

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 配置为使用公共(public)构造函数?也许还有其他方法可以做到吗?如果可能,我想避免使用属性装饰 WithReadonlyProperty 类。

最佳答案

Protobuf 可以使用私有(private)构造函数,所以也许您可以为 protobuf 创建私有(private)构造函数以供使用?

关于c# - protobuf-net 可以处理自动只读属性吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32097457/

相关文章:

c# - Protobuf-net 字段的惰性流式反序列化

c# - 使用 ProtoBuf-net 反序列化派生类型(字典)未正确设置对象字段

c# - 发布后谷歌登录不起作用

c# - 收集 lambda 内的异步结果

c# - MongoDB C# 驱动程序 : connection string for sharding over replica set

ios - 使用 Protobuf-net,我收到有关 List<Subclassable> 未知线路类型的异常

c# - 从 C++ 代码向 C# 代码发送回调时访问冲突读取位置 0x00000004

c# - 带有 IronPDF 的表格布局 C#

java - 从 Proto 转换为 XSD

protobuf-net - 找不到合适的默认类型编码。使用 protobuf 序列化时