我试图序列化以下类:为什么序列化时出现“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