gpt4 book ai didi

c# - 当键是枚举时,以 "Document"表示序列化字典

转载 作者:IT老高 更新时间:2023-10-28 13:21:18 26 4
gpt4 key购买 nike

我正在尝试将下面的“MyClass”写入 Mongo 集合:

public enum MyEnum { A, B, C };

public class MyClass
{
[BsonId(IdGenerator = typeof(StringObjectIdGenerator))]
public string Id { get; set; }

[BsonDictionaryOptions(DictionaryRepresentation.Document)]
public Dictionary<MyEnum , MyOtherClass> Items { get; set; }
}

public class MyOtherClass
{
public string MyProp { get; set; }
}

我想将它序列化为一个文档,因为这是最简洁的表示:

{
_id: "12345",
Items: {
A: {
MyProp: "foo"
},
B: {
MyProp: "bar"
},
C: {
MyProp: "baz"
},
}
}

Mongo 引擎在序列化时抛出异常:

When using DictionaryRepresentation.Document key values must serialize as strings.

所以,我想也许我可以注册一个约定,让枚举序列化为字符串:

var conventions = new ConventionPack();
conventions.Add(new EnumRepresentationConvention(BsonType.String));
ConventionRegistry.Register("Custom Conventions", conventions, type => type == typeof(MyClass));

不幸的是,这似乎没有任何效果,引擎也抛出了同样的异常。

当键是枚举类型时,有什么方法可以序列化 Document 表示中的字典?

最佳答案

您可以通过显式注册一个将您的 enum 序列化为字符串的序列化程序来实现。您可以使用带有 BsonType.String 表示的内置 EnumSerializer 类:

BsonSerializer.RegisterSerializer(new EnumSerializer<MyEnum>(BsonType.String));

关于c# - 当键是枚举时,以 "Document"表示序列化字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28245530/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com