【问题标题】:Testing null array index测试空数组索引
【发布时间】:2009-05-28 19:57:51
【问题描述】:

事情是这样的:

object[] arrayText = new object[1];

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

我们知道它将为空,但它会引发异常,但我不想在 try/catch 块中处理它,因为它嵌套在循环中,并且 try/catch 也会减慢它的速度看起来不太好:

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

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

感谢您的建议!

【问题讨论】:

    标签: c# arrays


    【解决方案1】:

    null不是这里的问题,只是索引无效。 C# 中的数组是从 0 开始的,因此如果创建一个元素为 1 的数组,则只有索引 0 有效:

    array[0] == null
    

    您可以通过在访问索引之前手动检查边界来避免这种情况:

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

    【讨论】:

    • 我使用了这个答案的变体:if (i >= rawDataTables.Length || rawDataTables[i].Rows.Count == 0)
    • 不客气...我假设您在评论中的示例中使用了“if (i = "... ;)
    • 哈哈不,我确实使用了“i >=”,因为如果发生“异常”,我唯一需要做的就是返回一个枚举值 =)
    【解决方案2】:
    object[] arrayText = new object[1];
    
    if (arrayText[0] == null)
    {
        MessageBox.Show("Is null");
    }
    

    试试看?数组是基于 0 的,因此尝试访问 arrayText[1] 会给您一个 OutOfBoundsException。并且 try/catch 并不会真正影响您的性能,那时堆栈中并没有太多。

    【讨论】:

    • 异常仍然很昂贵,例如异常对象必须被实例化(包括初始化)。不要将异常用于流控制 - 在这种情况下,这似乎是其中一种情况。
    • 我只是说当时的例外并不像他想象的那么昂贵。它不会有内部异常,也不会冒泡。但是在这种情况下使用 try/catch 并不是一个好主意,但不是因为他的推理 IMO。
    • 这显然只是一个显示问题的示例。你怎么能确定这不会发生在一个紧密的循环或其他异常昂贵的情况下?因此,推理没有错,即使异常实际上可能不会在特定情况下造成性能问题,我认为首先避免它是一个好习惯,也是恕我直言的方法。
    【解决方案3】:

    您正在访问数组边界之外的索引。数组初始值设定项采用一个数字表示元素的数量,而不是最大索引(如 VB.NET)。由于数组是从零开始的,因此在这种情况下,您的最大索引为 0。

    【讨论】:

    • @Adam Robinson:从技术上讲,你回答了这个问题。
    【解决方案4】:

    检查循环内数组的 .Length,或者更好的是,将循环参数设置为限制为数组的长度。

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

    【讨论】:

      【解决方案5】:

      我认为问题不在于 arrayText1 为空,而是 arrayText1 不存在 - 所以你应该得到一个 IndexOutOfRangeException 而不是空

      如果您遇到困难并且无法轻松更改代码以验证长度,您可以考虑添加一个检查 Length 属性的函数(请参见下面的代码段)或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);
              }
          }
      }
      

      【讨论】:

        【解决方案6】:

        如果您阅读有关正在引发的异常的描述,您会看到它是“索引超出了数组的范围。”

        new object[1] 表示数组只有一个元素。 (1 是计数)但是 C# 数组的开始索引是 0 而不是 1,所以一个元素的数组是索引 0。所以arrayText[0] 将返回 null 但arrayText[1] 将引发异常。

        【讨论】:

          【解决方案7】:

          我最近需要确定结构数组中的值是否在给定索引处“填充”。看看这个:

          //the struct holding the properties:
          struct Cities
                  {
                      public string name;
          
                      public int inhabitansNumber;
                  }
          
              Cities[] cities = new Cities[500]; // the struct array holding the cities
          
              int i = 0;
                                  for (i = 0; i < cities.Length; ++i)
                                  {
                                      if (cities[i].Equals(default(Cities)))
                                      {
                                          Console.WriteLine("Please enter the city name:");
                                          cities[i].name = Console.ReadLine();
                                          Console.WriteLine("Please enter population:");
                                          cities[i].inhabitansNumber = Convert.ToInt32(Console.ReadLine());
                                          Console.WriteLine("Values added successfuly!");
                                      }
                                  }
          

          【讨论】:

            猜你喜欢
            • 2020-07-26
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2019-04-21
            • 2020-01-19
            • 2016-07-25
            • 1970-01-01
            • 2011-06-11
            相关资源
            最近更新 更多