是否有可能为二维数组编写一个属性,该属性返回数组的特定元素?我很确定我不是在寻找索引器,因为该数组属于静态类。
是否有可能为二维数组编写一个属性,该属性返回数组的特定元素?我很确定我不是在寻找索引器,因为该数组属于静态类。
看起来你需要一个带参数的属性,这基本上就是索引器。但是,在C#中你不能编写静态索引器。
当然,你可以编写一个返回数组的属性 - 但我想你不想为了封装而这样做。
另一种选择是编写GetFoo(int x, int y)
和SetFoo(int x, int y, int value)
方法。
还有一种选择是在数组周围编写一个包装类型,并将其作为属性返回。包装类型可以具有索引器 - 也许只是一个只读的索引器,例如:
public class Wrapper<T>
{
private readonly T[,] array;
public Wrapper(T[,] array)
{
this.array = array;
}
public T this[int x, int y]
{
return array[x, y];
}
public int Rows { get { return array.GetUpperBound(0); } }
public int Columns { get { return array.GetUpperBound(1); } }
}
然后:
public static class Foo
{
private static readonly int[,] data = ...;
// Could also cache the Wrapper and return the same one each time.
public static Wrapper<int> Data
{
get { return new Wrapper<int>(data); }
}
}
return array[x, y];
,而不是return this[x, y];
(这将导致无限递归)。 - Douglasarray[x][y]
x 为行,y 为列。
public string this[int x, int y]
{
get { return TextArray[x, y]; }
set { TextArray[x, y] = value; }
}