c# - MessagePack 从 Dictionary<,> 继承的类中反序列化异常

标签 c# msgpack

嗨,我有一个类:

 public class Event : Dictionary<AttributeType, object>

AttributeType 是枚举

反序列化会抛出异常

var @event = new Event { { AttributeType.EventId, Guid.NewGuid() } };
MessagePackSerializer.Deserialize<Event(MessagePackSerializer.Serialize(@event));

异常消息是:

System.ArgumentException: 'The value "21" is not of type "BRCo.Core.Common.Enums.AttributeType" and cannot be used in this generic collection.'

但是当我使用这段代码时就可以了

var @event = new Event { { AttributeType.EventId, Guid.NewGuid() } };
MessagePackSerializer.Deserialize<Dictionary<AttributeType, object>>(MessagePackSerializer.Serialize(@event));

有什么帮助吗?

谢谢

最佳答案

感谢neuecc这就是答案

// create custom dictionary inherited formatter.
public class EventFormatter :DictionaryFormatterBase<AttributeType,object, Event>
{
   protected override Event Create(int count)
   {
       return new Event();
   }

   protected override void Add(Event collection, int index, AttributeType key, object value)
   {
       collection.Add(key, value);
   }
}

// and register it.
MessagePack.Resolvers.CompositeResolver.RegisterAndSetAsDefault(
new[] { new EventFormatter() },
new[] { StandardResolver.Instance });

关于c# - MessagePack 从 Dictionary<,> 继承的类中反序列化异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50100007/

相关文章:

c# - 如何在 C# 程序和 Node.js 程序之间使用 Msgpack?

c# - 将 XML 文档作为参数传递给 Nhibernate ICriteria?

c# - 验证年龄不低于 18 岁

c - msgpack 在 C 中打包 char 数组

c++ - Msgpack 中是否有版本控制功能

java - 在 Android 上使用 MessagePack

c++ - 如何使用 POD 数组对用户定义的 C++ 类进行 msgpack?

c# - 使用 C# 的 N 层?

c# - 使用 Entity Framework 插入引用其他表中的记录的记录

c# - 如何从 Web App 获取纬度/经度?