我正在使用带有矩形的xml序列化,但这会产生一些讨厌的XML ......
我的班级是这样的:
[Serializable]
public class myObject
{
public Rectangle Region { get; set; }
//Some other properties and methods...
}
并且在我将其序列化为XML时给我这个:
<myObject>
<Region>
<Location>
<X>141</X>
<Y>93</Y>
</Location>
<Size>
<Width>137</Width>
<Height>15</Height>
</Size>
<X>141</X>
<Y>93</Y>
<Width>137</Width>
<Height>15</Height>
</Region>
...
</myObject>
呸!
我希望我可以取消Size
上的Location
和Rectangle
属性,或者使用支持变量和[XmlIgnore]
来结束这样的事情:
[Serializable]
public class myObject
{
[XmlElement("????")]
public int RegionX;
[XmlElement("????")]
public int RegionY;
[XmlElement("????")]
public int RegionHeight;
[XmlElement("????")]
public int RegionWidth;
[XmlIgnore]
public Rectangle Region {get { return new Rectangle(RegionX, RegionY, RegionWidth, RegionHeight);}
//Some other properties and methods...
}
希望给我一些类似的东西:
<myObject>
<Region>
<X>141</X>
<Y>93</Y>
<Width>137</Width>
<Height>15</Height>
</Region>
...
</myObject>
代码不太好,但XML会由人编辑,所以最好能得到一些在那里工作的东西......
任何想法可能会出现在“????”中?或另一种方式吗?
我不想实现我自己的Rectangle
...
答案 0 :(得分:2)
感谢评论人员,我结束了一种DTO路线 - 我实现了自己的Struct - XmlRectangle
,保存了我需要用[Serializable]
修饰的四个int值。我添加了隐式转换运算符,因此我可以将其用作Rectangle
:
[Serializable]
public struct XmlRectangle
{
#endregion Public Properties
public int X {get; set; }
public int Y {get; set; }
public int Height { get; set; }
public int Width { get; set; }
#endregion Public Properties
#region Implicit Conversion Operators
public static implicit operator Rectangle(XmlRectangle xmlRectangle)
{
return new Rectangle(xmlRectangle.X, xmlRectangle.Y, xmlRectangle.Width, xmlRectangle.Height);
}
public static implicit operator XmlRectangle(Rectangle rectangle)
{
return result = new XmlRectangle(){ X = rectangle.X, Y = Rectangle.Y, Height = Rectangle.Height, width = Rectangle.Width };
}
#endregion Implicit Conversion Operators
}
然后,将其作为数据保存的类具有Rectangle
属性,将其作为XmlRectangle
公开给序列化器,如下所示:
[XmlElement("Region",typeof(XmlRectangle))]
public Rectangle Region { get; set; }