gpt4 book ai didi

c# - 为什么我在类属性上得到这个 "infinite loop"?

转载 作者:行者123 更新时间:2023-11-30 14:15:28 25 4
gpt4 key购买 nike

这是我的代码的属性:

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 { }
}

但它说:

An unhandled exception of type 'System.StackOverflowException' occurred in App_Code.rhj3qeaw.dll

为什么?我该如何解决?

编辑

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

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;
}
}

你在想什么?

最佳答案

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

   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

关于c# - 为什么我在类属性上得到这个 "infinite loop"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10056119/

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