Why would this simple code cause a stack overflow exception?

♀尐吖头ヾ 提交于 2019-12-25 18:29:15

问题


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?


回答1:


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



回答2:


Both get and set are recursive by calling themselves again. Try this instead:

string timeZone;

public string TimeZone
{
    get { return timeZone == null ? string.Empty : timeZone; }
    set { timeZone = value; }
}



回答3:


Try this

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

            return m_TimeZone;
        }
        set {m_TimeZone = value; }
    }

Where m_TimeZoneshould be associated variable

you are accessing same property TimeZone inside property TimeZone where you should be accessing and using associated variable




回答4:


In getter you ara accessing getter itself, this cause a recursive call to property getter itself

 if (TimeZone == null) 

Setter recursive as well

set { TimeZone = value; } 

So depends on calling code either getter or setter cause an stack overflow due to multiple calls to property (get_TimeZone() / set_TimeZone() methods under the hood).

So introduce backing field and use it in property, this is a commo technique I'm wondered why you are not aware of such simple stuff.



来源:https://stackoverflow.com/questions/7063827/why-would-this-simple-code-cause-a-stack-overflow-exception

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!