MessagePack-CSharp 序列化 System.Drawing.Color结构或Point结构

2021-04-23 02:30

阅读:521

标签:wing   ref   poi   system   初始   format   ack   private   pos   

如题,直接序列化会报错, 好像百度不到, 自已看了半个小时的官方文档, 摸索出来了, 需要 实现一个 IMessagePackFormatter 接口, 代码如下:

 

 1 using MessagePack;
 2 using MessagePack.Formatters;
 3 using MessagePack.Resolvers;
 4 using System;
 5 using System.Drawing;
 6 
 7 namespace MessageTest
 8 {
 9     internal class Program
10     {
11         private static void Main(string[] args)
12         {
13             // 不想用属性特性的话,就需要下两行代码.
14             var resolver = MessagePack.Resolvers.CompositeResolver.Create(
15                 StandardResolver.Instance,
16                 CompositeResolver.Create(ColorFormatter.Instance)
17             );
18 
19             var options = MessagePackSerializerOptions.Standard.WithResolver(resolver);
20             MessagePackSerializer.DefaultOptions = options;
21 
22             var bin = MessagePackSerializer.Serialize(new IntKeySample() { S = Color.Red });
23 
24             var obj = MessagePackSerializer.Deserialize(bin);
25 
26             Console.Write(obj.S);
27 
28             Console.Read();
29         }
30     }
31 
32     [MessagePackObject]
33     public class IntKeySample
34     {
35         [Key(3)]
36         public int A { get; set; }
37 
38         [Key(10)]
39         public int B { get; set; }
40 
41         [Key(1)]
42         //[MessagePackFormatter(typeof(ColorFormatter))] 序列化 像main函数中 初始化 resolver 后就不需要该行
43         public Color S { get; set; }
44     }
45 
46     public class ColorFormatter : IMessagePackFormatter47     {
48         public static ColorFormatter Instance = new ColorFormatter();
49 
50         public Color Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options)
51         {
52             var a = reader.ReadByte();
53             var r = reader.ReadByte();
54             var g = reader.ReadByte();
55             var b = reader.ReadByte();
56 
57             return Color.FromArgb(a, r, g, b);
58         }
59 
60         public void Serialize(ref MessagePackWriter writer, Color value, MessagePackSerializerOptions options)
61         {
62             writer.Write(value.A);
63             writer.Write(value.R);
64             writer.Write(value.G);
65             writer.Write(value.B);
66         }
67     }
68 }

 

MessagePack-CSharp 序列化 System.Drawing.Color结构或Point结构

标签:wing   ref   poi   system   初始   format   ack   private   pos   

原文地址:https://www.cnblogs.com/yangzn/p/14687495.html


评论


亲,登录后才可以留言!