【发布时间】:2015-04-16 17:36:16
【问题描述】:
我有一个类,我正在尝试使用 XMLSerializer 序列化和反序列化。该类如下所示:
namespace AutoCAD_Adapter
{
/// <summary>
/// Test class meant to be serialized to test serialization methods
/// </summary>
[Serializable]
public class SerializeTest// : ISerializable
{
#region class variables
private int x;
private int y;
#endregion
#region Constructors
public SerializeTest(int passedX, int passedY)
{
this.x = passedX;
this.y = passedY;
}
private SerializeTest()
{
}
#endregion
#region Public methods
public void setX(int x)
{
this.x = x;
}
public int getX()
{
return this.x;
}
public void setY(int y)
{
this.y = y;
}
public int getY()
{
return this.y;
}
#endregion
}
}
我知道 XMLSerialization 对没有空构造函数参数的类的问题,我通过创建私有默认构造函数来处理这些问题。请注意,这是我的实现:
public void XMLSave()
{
SerializeTest input = new SerializeTest(4, 8); //Object to serialize
using (MemoryStream stream = new MemoryStream())
{
XmlSerializer serializer = new XmlSerializer(st.GetType());
serializer.Serialize(stream, input);
stream.Position = 0;
SerializeTest output = serializer.Deserialize(stream) as SerializeTest;
MessageBox.Show(output.getX() + " " + output.getY(), "Output", MessageBoxButtons.OK);
}
}
在执行时,我希望 MessageBox 显示 (4, 8) 的值,但它显示的是 (0, 0)。我需要能够在整个序列化过程中保留对象值,最好是在维护 XML 序列化的同时。
【问题讨论】:
-
为什么你使用手动实现的属性访问器而不是自动生成的?据我所知,使用 public int X {get; set;} 总是使用 XML 序列化。
-
好点,我习惯了Java哈哈。谢谢
-
私人成员不被序列化。
XmlSerializer不需要Serializable属性。为什么不使用properties? -
使用属性解决了我的问题。指向作为答案发布的任何人
标签: c# xml serialization