属性
本页说明何时用属性封装内部状态或提供计算值。当前 SCL 支持显式 get / set、只读属性、自动属性和静态属性。访问器应在类的方法体内执行。外部命名实例上的属性读写仍有限制,公开工程代码应通过方法或字段出入。
显式属性
class AnalogChannel
{
private int _value = 0;
public int Value
{
get
{
return _value;
}
set
{
if (value < 0)
{
_value = 0;
}
else if (value > 1000)
{
_value = 1000;
}
else
{
_value = value;
}
}
}
public void Update(int next)
{
Value = next;
}
public int Read()
{
return Value;
}
}
AnalogChannel channel = new AnalogChannel();
channel.Update(1200);
int current = channel.Read();
Update / Read 在方法体内访问属性,这是当前稳定路径。不要写成 channel.Value = 1200。
自动属性和只读属性
class Counter
{
public int Value { get; set; }
public bool IsPositive
{
get
{
return Value > 0;
}
}
public void Increment()
{
Value = Value + 1;
}
public int Read()
{
return Value;
}
}
自动属性不要在声明后追加初始化表达式;需要初值时在构造函数或初始化方法中赋值。
静态计算属性
class MachineLimits
{
public static int Maximum = 1000;
public static int Warning
{
get
{
return Maximum * 9 / 10;
}
}
}
int warning = MachineLimits.Warning;
规则
get必须返回与属性声明一致的类型。set中的value是调用方写入值。- 访问器保持短小、确定,不执行通讯或其他慢操作。
- 需要向外报告写入失败时,提供返回
bool或状态码的方法。 - 接口可以声明
{ get; set; }签名;显式接口属性实现当前不可用。
当前不可用
- 外部命名实例上的属性读写(
instance.Threshold = 42); - 自定义索引器
this[int index]; init只写访问器、属性初始化器;- 读取属性时产生控制动作。