"No wire-value is mapped to the enum foo position 16" 错误是什么意思?

What does: "No wire-value is mapped to the enum foo position 16" error mean?

"No wire-value is mapped to the enum foo position 16"

这条错误信息是什么意思?

在我的特殊情况下,我有:

Additional information: No wire-value is mapped to the enum System.Drawing.ContentAlignment.0 at position 16

我知道,整数 0 在枚举中没有表示。我认为只要知道错误报告的含义就能让我更好地了解如何解决这个问题。

A "wire value" 是它将要使用的二进制表示形式 "on the wire",即在基础流中。在这种情况下,它使用 0 的事实意味着枚举的值为 0,但 它不期望 0,很可能是因为没有枚举定义的成员的值为 if 0。如果有,它将使用名称,而不是 System.Drawing.ContentAlignment.0。 protobuf-net 正在尝试应用强制值有意义的枚举规则(对于某些具有外部数据的场景,还可以选择允许您定义枚举值和连线值之间的映射)

有多种方法可以避免此问题:

  • 不要尝试序列化不存在的枚举值(或者:添加缺失值,如果您控制枚举)
  • 使用 Nullable<SomeEnum> (SomeEnum?) 序列化一个缺少 None 值的枚举,当你想表示
  • 使用 "shim" 属性 将类型公开为 int(或任何底层类型),这样 protobuf-net 就不会尝试应用枚举规则:

    public SomeEnum Foo {get;set;} // the actual member
    [ProtoMember(42)]
    private int FooSerialized { // only exists to help protobuf-net ignore the
        get { return (int)Foo; }// invalid values that the member might contain
        set { Foo = (SomeEnum)value; }
    }
    
  • 通过RuntimeTypeModel手动配置模型并通过将EnumPassthru设置为true[=22=告诉protobuf-net忽略该成员的枚举处理]

  • [Flags] 标记枚举声明,这将使 protobuf-net 自动启用 EnumPassThru