2015-05-15 22 views
1

我有一個ContactForm對象,它包含幾個嵌套的集合對象。當我嘗試序列化對象時,代碼卡在SectionCollectionObject內的循環中。C#如何在收集序列化期間停止循環代碼導致stackoverflow?

這裏是執行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); 
     } 
    } 
    // ... 
} 

節目被在「得到」語句停留在循環,直到它拋出一個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; 
    } 
} 
+0

您可以發佈您收到異常的堆棧跟蹤嗎? –

回答

3

您的索引總是無限循環,無論你是在序列化上下文中使用它。您可能想要像這樣調用其中的基本索引器:

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

謝謝修復它。 – robbins