加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 20:54:36 所属栏目:百科 来源:网络整理
导读:protobuf-net能否处理新的自动只读属性,即使用单个get和no私有集定义的自动属性? public class WithReadonlyProperty { public int ReadonlyProperty { get; } public WithReadonlyProperty(int val) { ReadonlyProperty = val; }} 当我这样做 RuntimeTypeM
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:Devprotobuf-netprotobuf-netSerializersPropertyDecorator.cs:line 46
   at ProtoBuf.Serializers.PropertyDecorator..ctor(TypeModel model,Type forType,IProtoSerializer tail) in c:Devprotobuf-netprotobuf-netSerializersPropertyDecorator.cs:line 32
   at ProtoBuf.Meta.ValueMember.BuildSerializer() in c:Devprotobuf-netprotobuf-netMetaValueMember.cs:line 375
   at ProtoBuf.Meta.MetaType.BuildSerializer() in c:Devprotobuf-netprotobuf-netMetaMetaType.cs:line 408
   at ProtoBuf.Meta.MetaType.get_Serializer() in c:Devprotobuf-netprotobuf-netMetaMetaType.cs:line 384
   at ProtoBuf.Meta.RuntimeTypeModel.Serialize(Int32 key,Object value,ProtoWriter dest) in c:Devprotobuf-netprotobuf-netMetaRuntimeTypeModel.cs:line 752
   at ProtoBuf.Meta.TypeModel.SerializeCore(ProtoWriter writer,Object value) in c:Devprotobuf-netprotobuf-netMetaTypeModel.cs:line 186
   at ProtoBuf.Meta.TypeModel.Serialize(Stream dest,SerializationContext context) in c:Devprotobuf-netprotobuf-netMetaTypeModel.cs:line 217
   at ProtoBuf.Serializer.Serialize[T](Stream destination,T instance) in c:Devprotobuf-netprotobuf-netSerializer.cs:line 86
    ...

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

解决方法

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读