简体   繁体   中英

How to serialize 64 bit enum in c#

[Flags]
Enum xyz : UInt64
{
  a = 1,
  .
  .
  . 
  b = 17179869184,
}  

for serializing I am using:

[ProtoContract]
class ABC
{
  [ProtoMember(1)]
  public xyz name;
}

name = xyz.b;

I am getting 0 on deserializing, so how can I get 64 bit number?

There's two different things we need to look at here; the first is: as long as you are assigning a non-zero value, for most values it should already work; the fact that you're seeing zero tells me that you're probably either not assigning a value in the first place (the default value for an enum is zero, even if you don't define anything with zero), or you are using a rewindable stream but have not rewound; this works on 2.4.4:

var obj = new ABC { name = xyz.a };
var ms = new MemoryStream();
Serializer.Serialize(ms, obj);
ms.Position = 0; // rewind
var clone = Serializer.Deserialize<ABC>(ms);
Console.WriteLine(clone.name); // a

However, there is a problem with larger numbers, as protobuf defines enums to be 32-bit. The v3 codebase works around this, so on the v3 previews, the same code will work fine with b too, but on v2 your value of b is currently too large and it causes an arithmetic overflow. In this scenario, the way I would approach this is with a shadow property:

public xyz name;

[ProtoMember(1)]
private ulong NameSerialized
{
    get => (ulong)name;
    set => name = (xyz)value;
}

This will work on either v2 or v3.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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