Why does my array initialization code cause a StackOverflowException to be thrown?
The following line of code in my class constructor is throwing a St开发者_如何学PythonackOverflowException:
myList = new string[]{}; // myList is a property of type string[]
Why is that happening? And what's the proper way to initialize an empty array?
UPDATE: The cause was in the setter, in which I was attempting to trim all values:
set
{
for (int i = 0; i < myList.Length; i++)
{
if (myList[i] != null) myList[i] = myList[i].Trim();
}
}
If myList is a property, did you check that the body of its setter does not recursively assign to itself instead of the backing field, as in:
private string[] _myList;
public string[] myList {
get {
return _myList;
}
set {
_myList = value;
}
}
myList = new string[0]
This should create an array with 0 elements.
EDIT: I just tested new string[] {}
and it works for me. Maybe the reason for your stackoverflow is elsewhere.
Can you post the rest of your method? Generally spoken, stackoverflows occur specially when performing a high number recursive method calls. Like this:
void MyMethod(int i)
{
MyMethod(i); //!StackOverFlow!
}
Your set
code doesn't actually assign anything, and refers to itself. I have a feeling you're misunderstanding how properties work. You need a backing variable which the property manipulates:
private string[] _myList;
And then you need to have your set
code work with that variable:
public string[] myList
{
get
{
return _myList;
}
set
{
_myList = value; // you have to assign it manually
for (int i = 0; i < _myList.Length; i++)
{
if (_myList[i] != null) _myList[i] = _myList[i].Trim();
}
}
}
If you try and access myList
, it's accessing itself, which then accesses itself, etc, leading to infinite recursion and a stack overflow.
It appears as though what @Jonas H said is accurate, you may be recursivly modifying the Property instead of its backing field.
WRONG
private String[] _myList;
public String[] myList
{
get {return _myList;}
set
{
for (int i = 0; i < myList.Length; i++)
{
if (myList[i] != null) myList[i] = myList[i].Trim();
}
}
}
RIGHT
private String[] _myList;
public String[] myList
{
get {return _myList;}
set
{
for (int i = 0; i < _myList.Length; i++)
{
if (_myList[i] != null) _myList[i] = _myList[i].Trim();
}
}
}
精彩评论