如何在C#中实现数组索引器 [英] How to implement Array indexer in C#

查看:394
本文介绍了如何在C#中实现数组索引器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以输入

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

事实上,尽管我不知道会需要多少内存,但我希望可以继续为Int.MaxValue添加尺寸.

In fact, I expect I could keep going adding dimensions to Int.MaxValue though I have no idea how much memory that would require.

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

How could I implement this variable indexing feature in my own class? I want to encapsulate a multi dimensional array of unknown dimensions and make it available as a property thus enabling indexing in this manner. Must I always know the size in which case how does Array work?

编辑

感谢您的评论,这就是我最终得到的内容-我确实想到了params,但是在不了解GetValue之后不知道该去哪里.

Thanks for the comments, here is what I ended up with - I did think of params but didn't know where to go after that not knowing about 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来初始化其元素的方法,这种方法已经解决了避免在我使用多数组(主要在单元测试中)时在类外进行for循环初始化代码.然后,我遇到了intellisense,看到了Initialize方法……尽管它将我限制为默认的构造函数和值类型.对于引用类型,将需要扩展方法.我仍然学到了一些东西,是的,当我尝试一个具有32个以上维度的数组时,出现了运行时错误.

TBH I don't really need this now. I was just looking for a way to extend Array to initialize its elements having resolved to avoid for loop initialization code outside the class whenever I was using a multi array (mainly in unit tests). Then I hit intellisense and saw the Initialize method...though it restricts me to a default constructor and value types. For reference types an extension method would be required. Still I learnt something and yes, there was a runtime error when I tried an array with more than 32 dimensions.

推荐答案

您可以使用varargs:

You could use varargs:

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

您必须处理以下事实:您自己认为indices可以具有任意长度,这是您认为合适的方式. (例如,对照数组等级检查indices的大小,将其键入为Array并使用

You'd have to handle the fact indices can have an arbitrary length yourself, in whicheevr way you feel is appropriate. (E.g. check the size of indices against the array rank, type it as Array and use GetValue().)

这篇关于如何在C#中实现数组索引器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆