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

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

 

 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<IntKeySample>(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 : IMessagePackFormatter<Color>
47     {
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结构

上一篇:wingdows 10 专业版 虚拟化方案 Hyper-V安装linux系统


下一篇:C# 实现简单的五子棋程序