2009-05-28 51 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); 
     } 
    } 
}