为什么XmlSerializer抛出InvalidOperationException? [英] Why is XmlSerializer throwing an InvalidOperationException?
本文介绍了为什么XmlSerializer抛出InvalidOperationException?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
public void Save() {
XmlSerializer Serializer = new XmlSerializer(typeof(DatabaseInformation));
/*
A first chance exception of type 'System.IO.FileNotFoundException' occurred in mscorlib.dll
A first chance exception of type 'System.IO.FileNotFoundException' occurred in mscorlib.dll
A first chance exception of type 'System.InvalidOperationException' occurred in System.Xml.dll
*/
// ....
}
如果需要的话,这是整个班级:
This is the whole class if you need it:
public class DatabaseInformation
{
/* Create new database */
public DatabaseInformation(string name) {
mName = name;
NeedsSaving = true;
mFieldsInfo = new List<DatabaseField>();
}
/* Read from file */
public static DatabaseInformation DeserializeFromFile(string xml_file_path)
{
XmlSerializer Serializer = new XmlSerializer(typeof(DatabaseInformation));
TextReader r = new StreamReader(xml_file_path);
DatabaseInformation ret = (DatabaseInformation)Serializer.Deserialize(r);
r.Close();
ret.NeedsSaving = false;
return ret;
}
/* Save */
public void Save() {
XmlSerializer Serializer = new XmlSerializer(typeof(DatabaseInformation));
if (!mNeedsSaving)
return;
TextWriter w = new StreamWriter(Path.Combine(Program.MainView.CommonDirectory.Get(), Name + ".xml"), false);
Serializer.Serialize(w, this);
w.Close();
NeedsSaving = false;
}
private string mName;
public string Name { get { return mName; } }
private bool mNeedsSaving;
public bool NeedsSaving { get { return mNeedsSaving; } set { mNeedsSaving = value; Program.MainView.UpdateTitle(value); } }
private bool mHasId;
public bool HasId { get { return mHasId; } }
List<DatabaseField> mFieldsInfo;
}
(PS:如果您有任何改进我的代码的技巧,请随时分享,我是C#初学者)
(PS: if you have any tips to improve my code feel free to share, I'm a C# beginner)
推荐答案
要序列化/反序列化您的类型,它需要具有无参数构造函数。在此处:
To serialize/deserialize your type it needs to have parameterless constructor. Check out here :
一个类必须有一个默认构造函数,才能由
XmlSerializer序列化。
A class must have a default constructor to be serialized by XmlSerializer.
这篇关于为什么XmlSerializer抛出InvalidOperationException?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文