C#:数组属性的getter和setter表达式

Gur*_*ofu 2 c#

如何CoolerFanIsOn在类中编写数组属性的getter和setter表达式CoolerSystem?我展示了非阵列属性的类似的所需表达IsOnLamp类.

class CoolerFan{

    bool isOn;
    public bool IsOn {
        get => isOn;
        set {
            isOn = value;
        }
    }
}

class CoolerSystem {

    private CoolerFan[] = new CoolerFan[5];
    private bool[] coolerFanIsOn = new Boolean[5];

    // invalid code from now

    public bool[] CoolerFanIsOn {
        get => coolerFanIsOn[number];
        set {
            coolerFanIsOn[number] = value;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Tim*_*ter 6

你可以使用索引器:

public class CoolerSystem
{
    private bool[] _coolerFanIsOn = new Boolean[5];

    public bool this[int index]
    {
        get => _coolerFanIsOn[index];
        set => _coolerFanIsOn[index] = value;
    }
}
Run Code Online (Sandbox Code Playgroud)

顺便说一句,在=>表达浓郁性质,其是在C#6新.如果你不能使用(setter在C#7中是新的)使用旧的语法,索引器与它无关(C#3):

public bool this[int index]
{
    get { return _coolerFanIsOn[index];  }
    set { _coolerFanIsOn[index] = value; }
}
Run Code Online (Sandbox Code Playgroud)

  • 有人在每个答案中投票,有什么不对吗?编辑回答澄清你不需要表达身体的getter/setter来使用索引器. (2认同)