为什么会这样简单的code导致堆栈溢出异常?堆栈、异常、简单、code

2023-09-06 19:21:36 作者:该不对傻子显示

堆栈溢出异常被抛出在 setter方法​​此属性的:

 公共字符串时区
{
    得到
    {
        如果(时区== NULL)
            返回 ;

        返回时区;
    }
    集合{时区=价值; }
}
 

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

我没有在这里看到的任何直接的递归。

如果有问题,在code,应该怎样使用我,而不是纠正它吗?

解决方案

 设置{时区=价值; }
 
打开网页提示堆栈溢出的操作步骤

的制定者是递归的。

您必须使用一个字段,如:

 字符串_timezone;

公共字符串时区
{
    得到
    {
        如果(_timezone == NULL)
            返回 ;

        返回_timezone;
    }
    集合{_timezone =价值; }
}
 

The stack overflow exception was thrown in the setter method of this property:

public string TimeZone
{
    get
    {
        if (TimeZone == null)
            return "";

        return TimeZone;
    }
    set { TimeZone = value; }
}

"An unhandled exception of type 'System.StackOverflowException' occurred"

I do not see any straightforward recursion here.

If there are problems with the code, what should I be using instead to correct it?

解决方案

set { TimeZone = value; }

The setter is recursive.

You must use a field like:

string _timeZone;

public string TimeZone
{
    get
    {
        if (_timeZone== null)
            return "";

        return _timeZone;
    }
    set { _timeZone= value; }
}