【问题标题】:Why I get this "infinite loop" on Class properties?为什么我在类属性上得到这个“无限循环”?
【发布时间】:2012-04-07 16:18:01
【问题描述】:

这是我代码中的属性:

public KPage Padre
{
    get
    {
        if (k_oPagina.father != null)
        {
            this.Padre = new KPage((int)k_oPagina.father);
        }
        else
        {
            this.Padre = null;
        }

        return this.Padre;
    }
    set { }
}

但它说:

App_Code.rhj3qeaw.dll 中出现“System.StackOverflowException”类型的未处理异常

为什么?我该如何解决?

编辑

改正代码后,这是我的实际代码:

private KPage PadreInterno;
public KPage Padre
{
    get
    {
        if (PadreInterno == null)
        {
            if (paginaDB.father != null)
            {
                PadreInterno = new KPage((int)paginaDB.father);
            }
            else
            {
                PadreInterno= null;
            }
        }

        return PadreInterno;
    }
}

你怎么看?

【问题讨论】:

  • else { PadreInterno= null; } 在更正后的代码中有什么用处?仅当 PadreInterno 还是 null 时才调用此代码:if (PadreInterno == null)。像这样简化if (PadreInterno == null && paginaDB.father != null) { PadreInterno = new KPage((int)paginaDB.father); } return PadreInterno;

标签: c# .net properties stack-overflow


【解决方案1】:

属性调用自身...通常属性调用底层字段:

   public KPage Padre
   {
       get
       {
           if (k_oPagina.father != null)
           {
               _padre = new KPage((int)k_oPagina.father);
           }
           else
           {
               _padre = null;
           }

           return _padre;
       }
       set { }
   }

   private KPage _padre;

您的旧代码递归调用Padre 属性的get,因此出现异常。

如果您的代码只“获取”并且不需要存储值,您也可以完全摆脱支持字段:

   public KPage Padre
   {
       get
       {
           return k_oPagina.father != null
              ? new KPage((int)k_oPagina.father)
              : (KPage)null;
       }
   }

也就是说,我会把它放在一个方法中。

这也是你前几天问的问题:

An unhandled exception of type 'System.StackOverflowException' occurred

【讨论】:

  • 延迟加载属性是很常见的;这是第一次要求它被构造并设置为内部属性,并且在所有未来的调用中都只是返回该属性。一些属性本身也是派生的数据,因此构造一个每次都返回的对象。 OP 的代码值得重新考虑,但它不是 100% 邪恶的。
  • @Servy 确实,我忘记了那个用例。请注意,这不是典型的延迟加载案例。
  • 同意,这就是为什么我说他应该重新考虑这是否是一个好模型,而不是直接拒绝它。
  • @Servy 我有点同意。应该考虑将每次返回不同对象的属性作为方法,但这只是偏好。
猜你喜欢
  • 2012-04-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-20
  • 1970-01-01
  • 1970-01-01
  • 2022-01-07
  • 2020-08-08
相关资源
最近更新 更多