访问和设置数组类型属性

Jun*_*mer 1 c# properties

我知道财产有以下形式:

class MyClass
{
    public int myProperty { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

这允许我这样做:

MyClass myClass = new MyClass();
myClass.myProperty = 5;
Console.WriteLine(myClass.myProperty); // 5
Run Code Online (Sandbox Code Playgroud)

但是,我可以做以下课程:

class MyOtherClass
{
    public int[,] myProperty
    {
        get
        {
            // Code here.
        }
        set
        {
            // Code here.
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

行为如下:

/* Assume that myProperty has been initialized to the following matrix:

myProperty = 1 2 3
             4 5 6
             7 8 9

and that the access order is [row, column]. */

myOtherClass.myProperty[1, 2] = 0;

/* myProperty = 1 2 3
                4 5 0
                7 8 9 */

Console.WriteLine(myOtherClass.myProperty[2, 0]); // 7
Run Code Online (Sandbox Code Playgroud)

提前致谢!

Ree*_*sey 5

您可以公开属性getter,并使用它:

class MyOtherClass
{
    public MyOtherClass()
    {
       myProperty = new int[3, 3];
    }

    public int[,] myProperty
    {
        get; private set;
    }
}
Run Code Online (Sandbox Code Playgroud)