[英]C#: Getter and setter expression for array property
如何在類CoolerSystem
編寫數組屬性CoolerFanIsOn
的getter和setter表達式? 我展示了Lamp
類的非數組屬性IsOn
的類似所需表達式。
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;
}
}
}
你可以使用索引器 :
public class CoolerSystem
{
private bool[] _coolerFanIsOn = new Boolean[5];
public bool this[int index]
{
get => _coolerFanIsOn[index];
set => _coolerFanIsOn[index] = value;
}
}
順便說一句, =>
是表達體性質 ,這是C#6中的新特性 。 如果你不能使用(setter在C#7中是新的)使用舊的語法,索引器與它無關(C#3):
public bool this[int index]
{
get { return _coolerFanIsOn[index]; }
set { _coolerFanIsOn[index] = value; }
}
您可以為您的班級編寫索引器
public bool this[int index]{
get { return coolerFanIsOn[index]; }
set { coolerFanIsOn[index] = value;}
}
也許這就是你想做的事情:
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;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.