问题
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