简体   繁体   English

Protobuf-Net初始化程序异常

[英]Protobuf-Net Initializer Exception

I am utilizing protobuf-net for a project, and have a class that contains a double?[] member. 我正在将protobuf-net用于一个项目,并且有一个包含double?[]成员的类。 As some of the values can be null, I need to run the following line of code: 由于某些值可以为null,因此我需要运行以下代码行:

RuntimeTypeModel.Default[typeof(MyType)][1].SupportNull = true;

I put this code in the static initializer for the class (eg, in static MyType() { ... } ), but when I run, I get an InvalidOperationException with the message "The type cannot be changed once a serializer has been generated". 我将此代码放在该类的静态初始化器中(例如,在static MyType() { ... } ),但是当我运行时,我收到一条InvalidOperationException消息,消息为“生成序列化器后,该类型不能更改”。 I suspect that this is due to the serializer being generated prior to the class being referenced for the first time. 我怀疑这是由于在第一次引用该类之前生成了序列化程序。 Does anyone know where to put this line of code so it always runs prior to serializer creation? 有谁知道将这行代码放在哪里,以便它始终在序列化程序创建之前运行?

Ah, I figured it out. 啊,我知道了。 The problem is that MyType inherits from BaseType. 问题是MyType继承自BaseType。 When I went to serialize/deserialize another type that inherits from BaseType, all of the serializers are built for all classes that inherit from BaseType. 当我要序列化/反序列化另一个从BaseType继承的类型时,所有序列化程序都是为从BaseType继承的所有类构建的。 Then, at a later time the first reference to MyType was happening (which calls the static constructor), but the serializer for that type was already built. 然后,在稍后的时间发生了对MyType的第一个引用(该调用称为静态构造函数),但是该类型的序列化程序已经构建。

To solve this I simply moved the aforementioned line of code into a BaseType static initializer. 为了解决这个问题,我仅将上述代码行移至BaseType静态初始化程序中。 To clarify, the following illustrates my solution: 为了澄清,以下说明了我的解决方案:

[ProtoContract]
[ProtoInclude(1, typeof(SubType1))]
[ProtoInclude(2, typeof(SubType2))]
public class BaseType {
    static BaseType() {
        // This runs prior to serializers being built,
        //     regardless of which subtype is used first
        RuntimeTypeModel.Default[typeof(SubType1)][1].SupportNull = true;
    }
    ...
}

[ProtoContract]
public class SubType1 : BaseType {
    [ProtoMember(1, OverwriteList = true)]
    public double?[] MyProp { get; set; }
    ...
}

[ProtoContract]
public class SubType2 : BaseType {
    ...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM