延迟加载Stackoverflow异常

本文关键字:异常 Stackoverflow 延迟加载 | 更新日期: 2023-09-27 18:06:18

我是延迟加载的新手,我一直在尝试在我的程序中实现它。然而,由于某种原因,我的程序抛出了一个StackoverflowException。我不知道该如何处理这个问题。

public new Field this[int key]
    {
        get
        {
            if (!this.Contains(key))
            {
                Field field = null;
                // The loading code of the field + assigning the field object.
                this.Add(field);
            }
            return this[key];
        }
    }

我确实意识到最后一行this[key]将一遍又一遍地返回,但我不确定如何修复它。

我的类是<int, Field>的一个KeyedCollection。

延迟加载Stackoverflow异常

KeyedCollection保护了Dictionary的属性。它返回包含所有条目的IDictionary<TKey, TItem>

public new Field this[int key]
{
    get
    {
        if (!this.Contains(key))
        {
            Field field = null;
            // The loading code of the field + assigning the field object.
            this.Add(field);
        }
        return Dictionary[key];
    }
}

这一行再次调用getter,这将导致递归调用。由于没有停止条件,它填满了堆栈的内存,因此出现了异常:

return this[key];

试着这样做:

return this.GetItem(key);