2009-05-28 43 views
4

事情是這樣的:測試空數組索引

object[] arrayText = new object[1]; 

if (arrayText[1] == null) 
{ 
    MessageBox.Show("Is null"); 
} 

我們知道,將是空的,但它拋出一個異常,但我不想處理它在try/catch塊,因爲這嵌套在一個循環中,並嘗試/ catch會減慢它,也看起來不太好:

object[] arrayText = new object[1]; 
try 
{ 
    if (arrayText[1] == null) 
    { 

    } 
} 
catch (Exception ex) 
{ 
    MessageBox.Show("Is null"); 
} 

謝謝你的建議!

回答

20

null這裏不是問題,但索引無效。在C#陣列0爲基礎的,因此,如果用1個元素,只有索引0創建陣列是有效的:

if (index < array.Length) { 
    // access array[index] here 
} else { 
    // no exception, this is the "invalid" case 
} 

array[0] == null 

可以訪問索引之前避免通過手動檢查的邊界

+0

我使用了這個答案的變體: if(i> = rawDataTables.Length || rawDataTables [i] .Rows.Count == 0) – Carlo 2009-05-28 20:10:24

+0

順便說一句,謝謝! – Carlo 2009-05-28 20:20:24

+0

不客氣......我假設你在評論中使用了「如果(我<=」在你的示例中,而不是「if(i> =」...;) – Lucero 2009-05-28 20:26:42

2

您正在訪問位於數組邊界之外的索引。數組初始值設定項爲元素數取一個數字,而不是最大索引(如VB.NET)。由於數組是基於零的,所以在這種情況下最大索引是0。

11
object[] arrayText = new object[1]; 

if (arrayText[0] == null) 
{ 
    MessageBox.Show("Is null"); 
} 

試試嗎?數組基於0,所以試圖訪問arrayText [1]會給你一個OutOfBoundsException。 try/catch不會真的影響你的表現,那裏沒有太多的東西。

1

檢查循環內數組的長度,或者更好的方法是將循環參數設置爲數組長度。

object[] arrayText = new object[1]; 
for (int i = 0; i < arrayText.Length; i++) 
{ 
    doWork(arrayText[i]); 
} 
0

如果您閱讀正在拋出的異常的描述,則會看到它是「索引超出了數組邊界」。

new object[1]表示該數組有一個元素。 (1是計數)但是,C#數組的開始索引在0不是1,因此一個元素的數組是索引0.因此arrayText[0]將返回空值,但arrayText[1]將引發異常。

1

我認爲問題不在於arrayText 1爲空,那就是arrayText 1犯規存在 - 所以,如果你是一個小溪,你應該得到一個IndexOutOfRangeException,而不是空

,並不能輕易改變的代碼以驗證長度,你可能會考慮添加一個函數,檢查長度屬性(見下面的snippit)或overloading operator [] ...這些都有點毛,但如果你在泡菜... :)

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 

namespace array 
{ 
    class Program 
    { 
     static object Index(object [] array, int idx) 
     { 
      if (idx >= array.Length) 
       return null; 
      else 
       return array[idx]; 
     } 
     static void Main(string[] args) 
     { 
      object[] blah = new object[10]; 
      object o = Index(blah, 10); 
     } 
    } 
}