我有一个包含多个嵌套集合对象的 ContactForm 对象。当我尝试序列化对象时,代码卡在 SectionCollectionObject 中的循环中。
这是执行 serialize() 调用的代码:
public static ContactForm SaveForm(ContactForm cf)
{
if (cf != null)
{
XmlSerializer xs = new XmlSerializer(cf.GetType());
StringBuilder sb = new StringBuilder();
using (StringWriter sw = new StringWriter(sb))
{
xs.Serialize(sw, cf);
}
}
// ...
}
程序在“get”语句处陷入循环,直到抛出 StackOverflowException。需要更改或添加什么代码才能通过这一点?
这是 SectionObjectCollection 类:
[Serializable, XmlInclude(typeof(Section))]
public sealed class SectionObjectCollection : Collection<Section>
{
public Section this[int index]
{
get {
return (Section)this[index]; //loops here with index always [0]
}
set {
this[index] = value;
}
}
}
这里是集合类继承自的 Section 类:
public class Section
{
public Section()
{
Questions = new QuestionObjectCollection();
}
public int SectionDefinitionIdentity {get;set;}
public string Name {get;set;}
public string Description {get;set;}
public bool ShowInReview {get;set;}
public int SortOrder {get;set;}
public QuestionObjectCollection Questions
{
get;
private set;
}
}
请您参考如下方法:
无论您是否在序列化上下文中使用它,您的索引器将始终无限循环。您可能想像这样调用其中的基本索引器:
public Section this[int index]
{
get {
return (Section)base[index]; //loops here with index always [0]
}
set {
base[index] = value;
}
}
