我正在使用带有矩形的 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>
讨厌!
我希望我可以抑制 Rectangle
上的 Size
和 Location
属性,或者使用支持变量和 [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
版本...
最佳答案
感谢大家的评论,我结束了一种 DTO 路线 - 我实现了自己的结构 - 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; }
关于c# - 没有新对象的子节点的 XML 序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13362631/