我会打字
Square[,,,] squares = new Square[3, 2, 5, 5];
squares[0, 0, 0, 1] = new Square();
事实上,我希望我可以继续向 Int.MaxValue 添加维度,尽管我不知道这需要多少内存。
如何在我自己的类中实现这个变量索引功能?我想封装一个未知维度的多维数组,并将其作为属性提供,从而以这种方式启用索引。我必须始终知道大小,在这种情况下 Array 如何工作?
编辑
感谢您的评论,这就是我的最终结果 - 我确实想到了参数,但在不知道 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 来初始化它的元素,并解决了在我使用多数组(主要是在单元测试中)时避免类外的循环初始化代码的问题。然后我点击了 intellisense 并看到了 Initialize 方法......虽然它限制了我使用默认构造函数和值类型。对于引用类型,将需要扩展方法。我仍然学到了一些东西,是的,当我尝试一个超过 32 维的数组时出现运行时错误。
最佳答案
数组类型很神奇——int[]
和 int[,]
是两种不同的类型,具有独立的索引器。
这些类型没有在源代码中定义;相反,它们的存在和行为由规范描述。
您需要为每个维度创建一个单独的类型——一个带有 this[int]
的 Matrix1
类,一个带有 Matrix2
的类this[int, int]
,等等。
关于c# - 如何在C#中实现数组索引器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18707951/