C# 如何阻止代码在集合序列化期间循环导致计算器溢出?

C# How do I stop code from looping during collection serialization causing a stackoverflow?

我有一个 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" 语句处陷入循环,直到它抛出 WhosebugException。需要更改或添加什么代码才能通过这一点?

这里是 SectionObjectCollection class:

[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;
        }
    }
}

这是集合 class 继承自的 Section class:

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;
    }
}