【问题标题】:MessagePack deserialize exception in inherited class from Dictionary<,>MessagePack 反序列化从 Dictionary<,> 继承的类中的异常
【发布时间】:2018-04-30 11:54:55
【问题描述】:

你好,我有这样的课:

 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));

有什么帮助吗?

谢谢

【问题讨论】:

    标签: c# msgpack


    【解决方案1】:

    感谢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 });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-13
      相关资源
      最近更新 更多