【问题标题】:C# return 2d array index from functionC#从函数返回二维数组索引
【发布时间】:2021-05-01 02:48:44
【问题描述】:

我有一个函数可以像这样返回二维数组的索引

public int[] getIndex()
{
    return new int[2] { i, j };
}

我希望能够使用这个函数直接访问二维数组的值,例如

var val = array[getIndex()]

但是 getIndex() 会抛出错误。有没有其他方法可以返回二维数组的键?还是我必须手动指定

 var val = array[getIndex()[0], getIndex()[1]]

【问题讨论】:

标签: c# arrays multidimensional-array


【解决方案1】:

你可以使用Array.GetValue():

int element = (int)array.GetValue(getIndex());

请注意,这需要强制转换。我在这个例子中使用了int,但是你需要为你的数组使用正确的类型。

如果你不喜欢强制转换,你可以写一个扩展方法:

public static class Array2DExt
{
    public static T At<T>(this T[,] array, int[] index)
    {
        return (T) array.GetValue(index);
    }
}

你会这样称呼:

var element = array.At(getIndex());

【讨论】:

    【解决方案2】:

    如果您在解决方案中手动指定索引,我建议您改用下面的代码。假设你 getIndex() 不仅仅返回一些内部变量,这段代码的性能会更好。

    var requiredItemIndex = getIndex();
    var val = array[requiredItemIndex[0], requiredItemIndex[1]];
    

    【讨论】:

      【解决方案3】:

      我会考虑创建一个自定义二维数组,并使用值元组或自定义点类型来描述索引。例如:

      public class My2DArray<T>{
      
          public int Width { get; }
          public int Height { get; }
          public T[] Data { get; }
          public My2DArray(int width, int height)
          {
              Width = width;
              Height = height;
              Data = new T[width * height];
          }
      
          public T this[int x, int y]
          {
              get => Data[y * Width + x];
              set => Data[y * Width + x] = value;
          }
          public T this[(int x, int y) index]
          {
              get => Data[index.y * Width + index.x];
              set => Data[index.y * Width + index.x] = value;
          }
      }
      

      这种方法的一个优点是您可以直接访问支持数组。因此,如果您只想处理所有项目,而不关心它们的位置,则可以使用普通循环。

      【讨论】:

        猜你喜欢
        • 2021-03-29
        • 2014-06-27
        • 2021-12-04
        • 2014-12-19
        • 2012-01-26
        • 1970-01-01
        • 1970-01-01
        • 2015-01-29
        相关资源
        最近更新 更多