为什么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
*/
// ....
}
如果你需要的话,这是整个班级:
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#初学者)
要序列化/反序列化你的类型,它需要有无参数的构造函数。 看看这里:
一个类必须有一个由XmlSerializer序列化的默认构造函数。
哦..我不知道它有额外的信息(不得不点击“查看详细信息”),神秘解决:
Message = SDB.DatabaseInformation不能被序列化,因为它没有无参数的构造函数。
我也遇到了这个异常,但并不是因为缺少默认的构造函数。 我有一些额外的属性(一个List
和Dictionary
),这些属性不是XML文档的一部分。
用[XmlIgnore]
装饰这些属性为我解决了这个问题。
上一篇: Why is XmlSerializer throwing an InvalidOperationException?
下一篇: Efficiently compute sum of N smallest numbers in an array