Best solution for XmlSerializer and System.Drawing.Color

前端 未结 4 1399
耶瑟儿~
耶瑟儿~ 2020-12-01 12:36

System.Drawing.Color objects apparently won\'t serialize with XmlSerializer. What is the best way to xml serialize colors?

4条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-01 13:10

    You could write a simple wrapper class for Color that exposes the ARGB values as properties. You could translate to/from the colors using from/to ARGB conversions (see docs). Something like:

    [Serializable] 
    public class ColorWrapper
    {
       private Color color;
    
       public ColorWrapper (Color color)
       {  
          this.color = color;
       }
    
       public ColorWrapper()
       {
        // default constructor for serialization
       }
    
       public int Argb
       { 
           get
           {
               return color.ToARGB(); 
           }
           set 
           {
               color = Color.FromARGB();
           }
       }
    }
    

    Probably want an accessor for the color too!

    Benefit of this is that the class can be used in all places you have to serialize colors. If you want to make the XML readable (rather than an arbitrary ARGB integer) you could use the to/from HTML methods as described by balabaster.

提交回复
热议问题