Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/308.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 在“中序列化词典”;文件「;表示,当键是枚举时_C#_.net_Mongodb_Mongodb .net Driver - Fatal编程技术网

C# 在“中序列化词典”;文件「;表示,当键是枚举时

C# 在“中序列化词典”;文件「;表示,当键是枚举时,c#,.net,mongodb,mongodb-.net-driver,C#,.net,Mongodb,Mongodb .net Driver,我正在尝试将下面的“MyClass”写入Mongo集合: public enum MyEnum { A, B, C }; public class MyClass { [BsonId(IdGenerator = typeof(StringObjectIdGenerator))] public string Id { get; set; } [BsonDictionaryOptions(DictionaryRepresentation.Document)] pu

我正在尝试将下面的“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; }
}
Mongo引擎在序列化时引发异常:

使用DictionaryRepresentation时。文档键值必须序列化为字符串

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

var conventions = new ConventionPack();
conventions.Add(new EnumRepresentationConvention(BsonType.String));
ConventionRegistry.Register("Custom Conventions", conventions, type => type == typeof(MyClass));
不幸的是,这似乎没有效果,引擎抛出了相同的异常


当键是枚举类型时,有没有办法序列化文档表示中的词典?

可以通过显式注册序列化程序来实现这一点,该序列化程序将
枚举
序列化为字符串。您可以将内置的
EnumSerializer
类与
BsonType.String
表示形式一起使用:

{
    _id: "12345",
    Items: {
        A: {
            MyProp: "foo"   
        },
        B: {
            MyProp: "bar"   
        },
        C: {
            MyProp: "baz"   
        },
    }
}
BsonSerializer.RegisterSerializer(new EnumSerializer<MyEnum>(BsonType.String));
BsonSerializer.RegisterSerializer(新的EnumSerializer(BsonType.String));

是否仅在此特定情况下将
MyEnum
序列化为字符串?还是到处都可以?@I3arnon也可以。