问题描述
|
是否可以为返回数组特定元素的2D数组编写属性?我很确定我不会在寻找索引器,因为它们的数组属于静态类。
解决方法
听起来您想要具有参数的属性-基本上就是索引器。但是,您不能在C#中编写静态索引器。
当然,您可以编写返回数组的属性-但我认为出于封装的原因,您不想这样做。
另一种选择是编写“ 0”和“ 1”方法。
另一个选择是在数组周围编写包装类型,并将其作为属性返回。包装器类型可以有一个索引器-可能只是一个只读索引器,例如:
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); }
}
}
,你的意思是这样吗?
array[x][y]
其中x是行,y是列。
,也许是这样的:
public string this[int x,int y]
{
get { return TextArray[x,y]; }
set { TextArray[x,y] = value; }
}