【问题标题】:Safe element of array access数组访问的安全元素
【发布时间】:2010-10-16 03:41:48
【问题描述】:

使用扩展方法或 LINQ 访问数组元素的安全方法是什么,而不抛出 IndexOutOfRangeExceptionTryParseTryRead

【问题讨论】:

    标签: c# .net arrays tryparse


    【解决方案1】:

    使用System.Linq ElementAtOrDefault 方法。它在不引发异常的情况下处理超出范围的访问。 在无效索引的情况下返回一个默认值。

    int[] array = { 4, 5, 6 };
    int a = array.ElementAtOrDefault(0);    // output: 4
    int b = array.ElementAtOrDefault(1);    // output: 5
    int c = array.ElementAtOrDefault(-1);   // output: 0
    int d = array.ElementAtOrDefault(1000); // output: 0
    

    另见DotNetPearls - ElementAt

    【讨论】:

      【解决方案2】:

      您可以使用以下扩展方法。

      public static bool TryGetElement<T>(this T[] array, int index, out T element) {
        if ( index < array.Length ) {
          element = array[index];
          return true;
        }
        element = default(T);
        return false;
      }
      

      例子:

      int[] array = GetSomeArray();
      int value;
      if ( array.TryGetElement(5, out value) ) { 
        ...
      }
      

      【讨论】:

      • 您应该将array[i] 更改为array[index]。另外,我认为你的逻辑是倒退的。如果 array.Length
      • @Jim,这就是我在喝完咖啡之前发布的内容。修正错别字
      • 可能还想检查索引 >= 0。
      【解决方案3】:

      将此扩展为空检查和超出范围检查。

      public static class ArraySafe
      {
          public static bool TryGetElement<T>(this T[] array, int index, out T element)
          {
              if(array == null || index < 0 || index >= array.Length)
              {
                  element = default(T);
                  return false;
              }
      
              element = array[index];
              return true;
          }
      }
      

      用法:

      public void Test()
          {
              int[] intAry = new Int32[10];
              int v;
              if (intAry.TryGetElement(6, out v))
              {
                  //here got value
              }
          }
      

      【讨论】:

        【解决方案4】:

        如果您想安全地循环遍历数组中的元素,只需使用枚举器即可:

        foreach (int item in theArray) {
           // use the item variable to access the element
        }
        

        【讨论】:

        • 不,我阅读了命令行参数并且必须确保下一个参数存在而不抛出异常(没有循环退出)
        猜你喜欢
        • 1970-01-01
        • 2020-11-15
        • 2013-04-25
        • 1970-01-01
        • 1970-01-01
        • 2012-05-16
        • 1970-01-01
        • 2014-04-26
        相关资源
        最近更新 更多