And*_*rew 3 c# properties multidimensional-array
是否可以为返回数组特定元素的2D数组编写属性?我很确定我不是在寻找索引器,因为它们属于静态类.
听起来你想要一个带参数的属性 - 这基本上就是索引器.但是,您无法在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); } }
}
Run Code Online (Sandbox Code Playgroud)
然后:
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); }
}
}
Run Code Online (Sandbox Code Playgroud)