简体   繁体   English

二维数组属性

[英]2D array property

Is it possible to write a property for a 2D array that returns a specific element of an array?是否可以为返回数组的特定元素的二维数组编写属性? I'm pretty sure I'm not looking for an indexer because they array belongs to a static class.我很确定我不是在寻找索引器,因为它们数组属于 static class。

It sounds like you want a property with parameters - which is basically what an indexer is.听起来你想要一个带参数的属性——这基本上就是索引器。 However, you can't write static indexers in C#.但是,您不能在 C# 中编写 static 索引器。

Of course you could just write a property which returns the array - but I assume you don't want to do that for reasons of encapsulation.当然,您可以只编写一个返回数组的属性 - 但我假设您出于封装的原因不想这样做。

Another alternative would be to write GetFoo(int x, int y) and SetFoo(int x, int y, int value) methods.另一种选择是编写GetFoo(int x, int y)SetFoo(int x, int y, int value)方法。

Yet another alternative would be to write a wrapper type around the array and return that as a property.另一种选择是在数组周围编写一个包装器类型并将作为属性返回。 The wrapper type could have an indexer - maybe just a readonly one, for example:包装器类型可以有一个索引器 - 可能只是一个只读的,例如:

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); } }
}

Then:然后:

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); }
    }
}

Do you mean something like this?你的意思是这样的吗?

array[x][y]

Where x is the row and y is the column.其中 x 是行,y 是列。

Maybe something like this?:也许是这样的?:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM