c# - MessagePack 反序列化从 Dictionary<,> 继承的类中的异常
问题描述
嗨,我有一个像这样的课程:
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 });
推荐阅读
- multidimensional-array - 如何在 Dyalog APL 中将三元组向量转换为 3xnx3 矩阵?
- c# - 如何使用键通过旋转来缩小对象?
- python - Pyhon:异常值:不支持的操作数类型 -:'str' 和 'int'
- javascript - 如何执行并行请求并返回包含 Javascript 中所有并行响应的对象?
- c++ - 使用 integer_sequence 专门化模板。GCC 与 MSVC
- google-places-api - 存储 Google 地方信息“place_id”并刷新它们
- html - html 和 css 类未显示在 html 模板邮件中
- php - 在 php foreach 循环中创建 Html 表
- load-testing - K6 用户和批处理概念
- html - 为什么我的图片和标题没有在 flexbox 中设置样式?