具有自动增量getter的StackOverflowException

Mar*_*rno 3 c#

看完这个问题后:

可以(a == 1 && a == 2 && a == 3)评估为真吗?

我试图覆盖getter以在C#中重现所需的行为.

使用此代码,我获得了我想要做的事情:

private static int myProperty;
public static int MyProperty
{
    get { myProperty++; return myProperty; }
    set { myProperty = value; }
}
static void Main(string[] args)
{
    if (MyProperty == 1 && MyProperty == 2 && MyProperty == 3)
    {
        Console.WriteLine("yohhooo");
    }
}
Run Code Online (Sandbox Code Playgroud)

但是由于我的第一次尝试,我提出了这个问题:

public static int MyProperty
{
    get { MyProperty++; return MyProperty; }
    set { MyProperty = value; }
}
static void Main(string[] args)
{
    if (MyProperty == 1 && MyProperty == 2 && MyProperty == 3)
    {
        Console.WriteLine("yohhooo");
    }
}
Run Code Online (Sandbox Code Playgroud)

它没有多少原因,我注意到一些奇怪的事情:

例如,如果我尝试使用Visual Studio 2017调试它并查看MyProperty初始值,程序将崩溃而不说任何内容.

所以我试图调试每条指令而不检查值,并注意到MyProperty++;getter内部是程序问题的原因,它会抛出这个错误:

System.StackOverflowException

但我无法理解为什么.如果我没有错,通过不声明MyProperty的初始值,它应该是0.所以从我的观点来看,如果它正在执行0 + 1我看不到问题,为什么要抛出该异常?

Jam*_*iec 6

你正在读自己的吸气剂

public static int MyProperty
{
    get { MyProperty++; return MyProperty; }
    set { MyProperty = value; }
}
Run Code Online (Sandbox Code Playgroud)

调用get,调用get,无限调用get ad - 最终将溢出堆栈.