为什么我的 属性 会出现 StackOverflowException?

Why do I get a StackOverflowException with my property?

请向我解释为什么这段代码会产生 WhosebugException

其中一行有错误,正如我使用注释显示的那样。但是我不明白为什么这会给我一个 WhosebugException.

class TimePeriod
{
    private double seconds;

    public double hour
    {
        get { return hour / 3600; }  // should be :  get { return seconds / 3600; }
        set { seconds = value * 3600; }
    }
}

class Program
{        
    static void Main()
    {
        TimePeriod t = new TimePeriod();
        t.hour = 5;
        System.Console.WriteLine("Time in hours: " + t.hour);
    }
} 

这会产生堆栈溢出,因为在您尝试获取 hour 时会进行递归调用。

此处t.hour,你尝试获取hour的值。我们称之为 getter,即 returns hour / 3600。这将再次调用 hour 等等,直到堆栈溢出。

在您的 hour 属性 getter 中,您正在访问 hour 属性,这会创建一个无限循环。似乎您甚至在提供正确答案的错误代码之后也有评论。