简体   繁体   English

如何在c#中序列化64位枚举

[英]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?我在反序列化时得到 0,那么我怎样才能得到 64 位数字?

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:这适用于 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.但是,较大的数字存在问题,因为 protobuf枚举定义为 32 位。 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. v3 代码库解决了这个问题,因此在 v3 预览版中,相同的代码也适用于b ,但在 v2 上,您的b值当前太大,会导致算术溢出。 In this scenario, the way I would approach this is with a shadow property:在这种情况下,我将采用的方法是使用 shadow 属性:

public xyz name;

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

This will work on either v2 or v3.这适用于 v2 或 v3。

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

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