C#MongoDB尝试将enum:uint32转换为int32并崩溃

我有一个枚举

public enum MyEnum : uint
    {
        ValueA = 1233104067,ValueB= 1119849093,ValueC= 2726580491
}

每当我用这个枚举创建一个类并尝试将其存储到数据库中时.
 例如

class MyClass {
    public MyEnum newValue = MyEnum.ValueC;
}

它将使程序崩溃并出现此错误

Unhandled Exception: System.OverflowException: Value was either too large or too small for an Int32.
   at System.Convert.ThrowInt32OverflowException()
   at System.UInt32.System.IConvertible.ToInt32(IFormatProvider provider)
   at MongoDB.Bson.Serialization.Serializers.EnumSerializer`1.Serialize(BsonSerializationContext context,BsonSerializationArgs args,TEnum value)

它尝试将uint值转换为int,但它们太大而且会抛出异常.

我该如何解决这个问题?

谢谢.

解决方法

MongoDB将数据存储为BSON,即 doesn’t have unsigned integer types.

你有三个选择:

>注释您的未签名类型.

如果使用驱动程序v2.4.3或更早版本:

public class MyClass
{
    [BsonRepresentation(BsonType.Int32,AllowOverflow = true)]
    public MyEnum Value1 = MyEnum.ValueC;

    [BsonRepresentation(BsonType.Int32,AllowOverflow = true)]
    public uint Value2 = uint.MaxValue;
}

不幸的是,驱动程序v2.4.4及更高版本中的序列化程序不尊重
AllowOverflow,无论如何抛出异常(测试和
确认,感谢dnickless指出这一点).这是一个解决方法
(以牺牲一些浪费的空间为代价):

public class MyClass
{
    [BsonRepresentation(BsonType.Int64)]
    public MyEnum Value1 = MyEnum.ValueC;

    [BsonRepresentation(BsonType.Int64)]
    public uint Value2 = uint.MaxValue;
}

>使用签名类型并在适当的时候转换.

// Defaults to int.
public enum MyEnum
{
    ValueA = 1233104067,ValueB = 1119849093,ValueC = unchecked((int)2726580491)
}

// Usage.
uint a = (uint)MyEnum.ValueA;
uint b = (uint)MyEnum.ValueB;
uint c = unchecked((uint)MyEnum.ValueC);
uint d = (uint)document["MyProperty"].AsInt32; // Reading from a BsonDocument.

>手动序列化(UInt32Serializer,UInt64Serializer等).

相关文章

一.C语言中的static关键字 在C语言中,static可以用来修饰局...
浅谈C/C++中的指针和数组(二) 前面已经讨论了指针...
浅谈C/C++中的指针和数组(一)指针是C/C++...
从两个例子分析C语言的声明 在读《C专家编程》一书的第三章时...
C语言文件操作解析(一)在讨论C语言文件操作之前,先了解一下...
C语言文件操作解析(三) 在前面已经讨论了文件打开操作,下面...