如何阻止代码在集合序列化期间循环导致stackoverflow ?

本文关键字:循环 stackoverflow 代码 何阻止 集合 序列化 | 更新日期: 2023-09-27 17:49:28

我有一个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;
    }   
} 

如何阻止代码在集合序列化期间循环导致stackoverflow ?

无论您是否在序列化上下文中使用它,您的索引器将始终无限循环。你可能想在里面像这样调用基索引器:

public Section this[int index]
{            
    get {
        return (Section)base[index]; //loops here with index always [0]
    }
    set {
        base[index] = value;
    }
}