2D Array Property

Is it possible to write a property for a 2D array that returns a specific element of the array? I am sure that I am not looking for an indexer because they belong to a static class.

+3
source share
3 answers

It looks like you want a property with parameters, which is basically an index. However, you cannot write static indexes in C #.

Of course, you could just write a property that returns an array, but I assume you don't want to do this for encapsulation reasons.

Another alternative would be to write methods GetFoo(int x, int y)and 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); }
    }
}
+6

- ?

array[x][y]

x - , y - .

+1

Maybe something like this ?:

public string this[int x, int y] 
{
   get { return TextArray[x, y]; }
   set { TextArray[x, y] = value; }
}
0
source

All Articles