如何在 C# 中实现数组索引器

本文关键字:数组 索引 实现 | 更新日期: 2023-09-27 18:30:53

我可以输入

Square[,,,] squares = new Square[3, 2, 5, 5];
squares[0, 0, 0, 1] = new Square();

事实上,我希望我可以继续向 Int.MaxValue 添加维度,尽管我不知道这需要多少内存。

如何在自己的类中实现此变量索引功能? 我想封装一个未知维度的多维数组,并将其作为属性提供,从而以这种方式实现索引。我必须始终知道大小,在这种情况下数组如何工作?

编辑

感谢您的评论,这就是我最终得到的 - 我确实想到了参数,但在不知道 GetValue 的情况下不知道该去哪里。

class ArrayExt<T>
{
  public Array Array { get; set; }
  public T this[params int[] indices] 
  {
      get { return (T)Array.GetValue(indices); }
      set { Array.SetValue(value, indices);}
  }
}
ArrayExt<Square> ext = new ArrayExt<Square>();
ext.Array = new Square[4, 5, 5, 5];
ext[3, 3, 3, 3] = new Square();

TBH 我现在真的不需要这个。我只是在寻找一种扩展 Array 以初始化其元素的方法,每当我使用多数组(主要是在单元测试中)时,我都会解析为避免类外的循环初始化代码。然后我点击智能感知并看到了初始化方法...尽管它将我限制为默认构造函数和值类型。对于引用类型,需要扩展方法。我仍然学到了一些东西,是的,当我尝试超过 32 维的数组时出现运行时错误。

如何在 C# 中实现数组索引器

数组类型是神奇的 – int[]int[,]是两种不同的类型,具有单独的索引器。
这些类型未在源代码中定义;相反,它们的存在和行为由规范描述。

您需要为每个维度创建一个单独的类型——一个带有this[int]Matrix1类、一个带有this[int, int]Matrix2类,等等。

你可以使用 varargs:

class Squares {
    public Square this[params int[] indices] {
        get {
            // ...
        }
    }
}

你必须处理这样一个事实indices自己可以有一个任意的长度,你觉得以这种方式是合适的。(例如,根据数组等级检查indices的大小,将其键入为Array并使用GetValue()

使用this[]运算符:

public int this[int i, int j]
{
    get {return 1;}
    set { ; }
}

请注意,一个运算符中不能有可变数量的维度 - 您必须分别对每个方法进行编码:

public int this[int i, int j, int k]
{
    get {return 1;}
    set { ; }
}
public int this[int i, int j]
{
    get {return 1;}
    set { ; }
}
public int this[int i]
{
    get {return 1;}
    set { ; }
}

我希望我可以继续向 Int.MaxValue 添加维度

你错了:

一个数组最多可以有 32 个维度。