gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 23:37:04 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com