我試圖序列化以下類:爲什麼序列化時出現「System.StackOverflowException was unhandled」異常?
[Serializable()]
public class BindingNode : IEnumerable<BindingNode>
{
public BindingNode()
{
}
IEnumerator IEnumerable.GetEnumerator()
{
throw new NotImplementedException();
}
public IEnumerator<BindingNode> GetEnumerator()
{
throw new NotImplementedException();
}
public void Add(BindingNode item)
{
throw new NotImplementedException();
}
}
這本來是一個ICollection的,而不是一個IEnumerable,但我去掉儘可能我可以我的代碼只保留什麼原因造成的錯誤。這裏就是發生異常的代碼:
private void button1_Click(object sender, EventArgs e)
{
BindingNode node = new BindingNode();
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
Stream stream = File.Open(saveFileDialog1.FileName, FileMode.Create);
XmlSerializer xmlFormatter = new XmlSerializer(node.GetType());
xmlFormatter.Serialize(stream, node);
stream.Close();
}
}
作爲一個方面說明,您不需要爲XmlSerializer標記您的類Serializable。 – 2010-08-10 21:14:01
此外,您應該使用「使用」塊來清理流,而不僅僅是.Close。正如你所看到的,序列化代碼可能會拋出可能使文件打開的句柄。 – McKay 2010-08-10 21:34:39