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

时间:2017-10-26 07:58:17

标签: c#

如何在类CoolerFanIsOn中编写数组属性CoolerSystem的getter和setter表达式?我为IsOn类的非数组属性Lamp展示了类似的所需表达式。

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

3 个答案:

答案 0 :(得分:6)

您可以使用indexer

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

    public bool this[int index]
    {
        get => _coolerFanIsOn[index];
        set => _coolerFanIsOn[index] = value;
    }
}

顺便说一下,=>expression bodied properties,它们是C#6中的新功能。如果你不能使用(setter在C#7中是新的)使用旧的语法,索引器与它无关(C#3):

public bool this[int index]
{
    get { return _coolerFanIsOn[index];  }
    set { _coolerFanIsOn[index] = value; }
}

答案 1 :(得分:2)

您可以为班级编写索引器

public bool this[int index]{
   get { return coolerFanIsOn[index]; }
   set { coolerFanIsOn[index] = value;}
}

答案 2 :(得分:0)

也许这就是你想做的事情:

class CoolerSystem
{

    private CoolerFan[] _fans = new CoolerFan[5];

    private bool[] _coolerfanIsOn;

    public bool[] CoolerFanIsOn
    {
        get { return _coolerfanIsOn; }
        set
        {
            _coolerfanIsOn = value;
        }
    }

    public bool GetFanState(int number)
    {
        return CoolerFanIsOn[number];
    }

    public void SetFanState(int number, bool value)
    {
        CoolerFanIsOn[number] = value;
    }
}