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

标签 c# serialization collections .net-4.5

我有一个包含多个嵌套集合对象的 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;
    }
}

关于C# 如何阻止代码在集合序列化期间循环导致计算器溢出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30265629/

相关文章:

c# - 如何读取多个文件txt c#

c# - 移动后正确设置文件的权限

c# - 无法在 C# 中访问 Amazon SQS 消息属性

c# - DataGridViewCheckBoxColumn : FormatException on boolean-column

c# - XML 序列化在 null 或空值上强制完全结束标记

java - 在java中通过网络发送列表

java - ASSIGNRES 类型的比较方法未定义

java - 使用 Jackson 将列表序列化为 xml,无需注释?

java - 自 Java5 + 菱形运算符以来初始化通用集合的方法