2010-05-26 68 views
1

的代碼在我的類的構造函數下面的行拋出一個StackOverflowException:爲什麼我的數組初始化代碼會導致拋出StackOverflowException?

myList = new string[]{}; // myList is a property of type string[] 

這是爲什麼發生?什麼是初始化空數組的正確方法?


UPDATE:的原因是在設定器,其中我試圖將修剪的所有值:

set 
{ 
    for (int i = 0; i < myList.Length; i++) 
    { 
     if (myList[i] != null) myList[i] = myList[i].Trim(); 
    } 
} 
+0

你能發佈你的構造函數嗎?看起來問題的真正原因可能在另一條線上。 – Syntactic 2010-05-26 17:17:04

回答

8

如果myList中是一個屬性,你檢查它的制定者的身體不遞歸分配給本身,而不是支持字段的,如:

private string[] _myList; 

public string[] myList { 
    get { 
    return _myList; 
    } 
    set { 
    _myList = value; 
    } 

}

+1

+1用於在這種特殊情況下識別問題。如果你寫了正確的支持字段,這將是完美的。 – Simon 2010-05-26 17:21:11

2
myList = new string[0] 

這應該與0個元素創建一個數組。

編輯:我剛剛測試new string[] {}它適用於我。也許你的stackoverflow的原因是在別處。

你可以發表你的方法的其餘部分?一般來說,當執行大量遞歸方法調用時,特別會發生stackoverflow。就像這樣:

void MyMethod(int i) 
{ 
    MyMethod(i); //!StackOverFlow! 
} 
+0

不,仍然得到StackOverflowException。 – MCS 2010-05-26 17:13:04

1

看起來好像@Jonas H說的是準確的,你可能會遞歸地修改屬性而不是它的後臺字段。

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(); 
     } 
    } 
} 
2

set代碼實際上並沒有分配任何東西,是指本身。我有一種感覺,你誤解了屬性的工作原理。您需要該財產操縱後備變量:

private string[] _myList; 

然後你需要讓你與該變量set代碼工作:

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

如果您嘗試訪問myList,它的訪問本身,然後訪問自己等,導致無限遞歸和堆棧溢出。

+0

經過測試;我可以說這是最可能的原因,如果不是原因。 – BoltClock 2010-05-26 17:30:14

相關問題