Why would this simple code cause a stack overflow exception?
The stack overflow exception was thrown in the setter method开发者_JAVA技巧 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; }
}
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; }
}
Try this
public string TimeZone
{
get
{
if (m_TimeZone == null)
return "";
return m_TimeZone;
}
set {m_TimeZone = value; }
}
Where m_TimeZone
should be associated variable
you are accessing same property TimeZone
inside property TimeZone
where you should be accessing and using associated variable
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.
精彩评论