[英]C#: Getter and setter expression for array property
How can I write the getter and setter expression for array property CoolerFanIsOn
in the class CoolerSystem
? 如何在类
CoolerSystem
编写数组属性CoolerFanIsOn
的getter和setter表达式? I showed the similar desired expression for non-array property IsOn
of Lamp
class. 我展示了
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;
}
}
}
You can use indexer : 你可以使用索引器 :
public class CoolerSystem
{
private bool[] _coolerFanIsOn = new Boolean[5];
public bool this[int index]
{
get => _coolerFanIsOn[index];
set => _coolerFanIsOn[index] = value;
}
}
Btw, the =>
are expression bodied properties which were new in C#6. 顺便说一句,
=>
是表达体性质 ,这是C#6中的新特性 。 If you can't use (setter was new in C#7) use the old syntax, indexers have nothing to do with it(C#3): 如果你不能使用(setter在C#7中是新的)使用旧的语法,索引器与它无关(C#3):
public bool this[int index]
{
get { return _coolerFanIsOn[index]; }
set { _coolerFanIsOn[index] = value; }
}
You can write an indexer for your class 您可以为您的班级编写索引器
public bool this[int index]{
get { return coolerFanIsOn[index]; }
set { coolerFanIsOn[index] = value;}
}
Maybe this is what you would like to do: 也许这就是你想做的事情:
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.