我尝试将自定义对象的两个列表保存为List<Vechicle>
类型的第一个列表。
XmlSerializer SerializerObjVechicle = new XmlSerializer(typeof(List<Vechicle>));
然后我收到错误
&#34;未处理的类型异常 &#39; System.Windows.Markup.XamlParseException&#39;发生在 PresentationFramework.dll&#34;
这是我的车辆类
[Serializable]
public class Vechicle
{
private int _Id;
private String _Registration;
public Vechicle(int id,String registration)
{
Id = id;
Registration = registration;
}
public override string ToString()
{
return Id.ToString() + " " + Registration;
}
#region getters/setters
public int Id{
get { return _Id; }
set { _Id = value; }
}
public String Registration
{
get { return _Registration; }
set { _Registration = value; }
}
#endregion
}
}
答案 0 :(得分:0)
需要添加不带参数的构造函数。 或者从ISerializable接口继承类。
http://msdn.microsoft.com/en-us/library/vstudio/ms233843(v=vs.110).aspx
答案 1 :(得分:0)
bogza.anton的回答是对的,你需要提供一个没有参数的构造函数,我给出一个这样的样本:
[Serializable]
public class Vechicle
{
private int _Id;
private String _Registration;
public Vechicle()
{
_Id = 1;
_Registration = "default name";
}
public Vechicle(int id, String registration)
{
Id = id;
Registration = registration;
}
public override string ToString()
{
return Id.ToString() + " " + Registration;
}
#region getters/setters
public int Id
{
get { return _Id; }
set { _Id = value; }
}
public String Registration
{
get { return _Registration; }
set { _Registration = value; }
}
#endregion
}
private void button1_Click(object sender, EventArgs e)
{
List<Vechicle> vList = new List<Vechicle>()
{
new Vechicle(),
new Vechicle(),
new Vechicle{Id=2, Registration="hello"},
new Vechicle{Id = 100, Registration="world"}
};
XmlSerializer SerializerObjVechicle = new XmlSerializer(vList.GetType());
FileStream fs = new FileStream("d:\\test.xml", FileMode.OpenOrCreate);
SerializerObjVechicle.Serialize(fs, vList);
}
我的测试结果如下: