为什么我在Class属性上得到这个"无限循环"?

mar*_*zzz 3 .net c# stack-overflow properties

这是我的代码的属性:

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 { }
}
Run Code Online (Sandbox Code Playgroud)

但它说:

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

你有什么想法?

Ada*_*rth 7

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

   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;
Run Code Online (Sandbox Code Playgroud)

您的旧代码是递归调用get的的Padre财产,因此例外.

如果您的代码只是"获取"而不需要存储该值,您还可以完全摆脱支持字段:

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

那就是说,我把它放在一个方法中.

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

发生了'System.StackOverflowException'类型的未处理异常