简体   繁体   English

protobuf-net:枚举类型转换错误

[英]protobuf-net : enum type conversion error

namespace MyNamespace                                               
{       

    public enum MyEnum
    {
        EnumName1 = 1,    
        EnumName2 = 2,
        ...

    [ProtoContract(Name=@"MyClassProto")]                                               
    [Serializable]                                                                                  
    public class MyClass : IExtensible                                              
    {                                                                                                                                           
        [ProtoMember(1, IsRequired = false, Name = @"MyEnumProperty", DataFormat = ProtoBuf.DataFormat.Default)]
        [System.ComponentModel.DefaultValue(1)]                                                     
        public MyEnum MyEnumProperty;                               
        ...



  var myObjectIn = new MyClass
  {
      MyEnumProperty = MyEnum.EnumName1,
      ...
  };

  MyClass myObjectOut;
  using (var stream = new MemoryStream())
  {
      ProtoBuf.Serializer.Serialize(stream, myObjectIn);
      stream.Seek(0, SeekOrigin.Begin);
      myObjectOut = ProtoBuf.Serializer.Deserialize<MyClass>(stream);
  }

System.InvalidCastException : Invalid cast from 'System.Int32' to 'MyNamespace.MyEnum'. System.InvalidCastException:从'System.Int32'到'MyNamespace.MyEnum'的无效转换。

I am using protobuf-net v2.1.0, and depending on approach I get two distinct ProtoException s. 我正在使用protobuf-net v2.1.0,并且根据方法,我得到两个不同的ProtoException Either No wire-value is mapped to the enum MyEnum , or No parameterless constructor found . No wire-value is mapped to the enum MyEnum ,或者No parameterless constructor found Reasons are: the default int value 0 is not a constant in your enum type, or you haven't assigned a default value to it in a parameter constructor. 原因是:默认int值0在您的枚举类型中不是常量,或者您没有在参数构造函数中为其分配默认值。

Workaround (logical or): 解决方法(逻辑或):

public enum MyEnum { EnumName1 = 1, EnumName2 = 2, @default = 0 }

or 要么

public MyClass() { MyEnumProperty = MyEnum.EnumName1 }

From ECMA-334 C# Language Specification 来自ECMA-334 C#语言规范

  1. An enum declaration that does not explicitly declare an underlying type has an underlying type of int. 没有显式声明基础类型的枚举声明具有基础类型int。 If the enum member is the first enum member declared in the enum type, its associated value is zero. 如果枚举成员是用枚举类型声明的第一个枚举成员,则其关联值为零。
  2. Enums are used for “multiple choice” scenarios, in which a runtime decision is made from a fixed number of choices that are known at compile-time 枚举用于“多选”方案,在这种情况下,运行时决策由编译时已知的固定数量的选择决定

So, your enum with a runtime value you haven't defined as a compile-time constant, imo, is a bad enum. 因此,带有尚未定义为编译时常量imo的运行时值的枚举是一个不好的枚举。

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

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