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

我可以打字

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

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

我怎么能在我自己的类中实现这个变量索引function? 我想封装一个未知维度的多维数组,并使其可用作属性,从而以这种方式启用索引。 我必须始终知道大小在哪种情况下Array如何工作?

编辑

感谢您的评论,这就是我最终的结果 – 我确实想到了params,但在不了解GetValue之后不知道该去哪里。

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

TBH我现在不需要这个。 我只是在寻找一种方法来扩展Array来初始化它已解析的元素,以避免在我使用多数组(主要是在unit testing中)时类外的循环初始化代码。 然后我点击intellisense并看到了Initialize方法……虽然它将我限制为默认构造函数和值类型。 对于参考类型,将需要扩展方法。 我仍然学到了一些东西,是的,当我尝试一个超过32维的数组时,出现了运行时错误。

你可以使用varargs:

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

你必须处理事实indices你自己可以有任意长度,你认为合适的方式。 (例如,检查数组排名的indices大小,将其键入Array并使用GetValue() 。)

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

您需要为每个维度创建一个单独的类型 – 一个带有this[int]Matrix1类,一个带有this[int, int]Matrix2类,依此类推。

使用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个维度。