属性(Prop)
prop 把「读起来像字段、写起来可带逻辑」的成员做成一等公民。自动属性单行即可声明,访问器体在需要时才出现。
自动属性与表达式体
本页用一支温度计做贯穿例,完整的声明长这样,下面各节逐个拆开讲:
class Thermometer
{
public prop Celsius: float = 0.0;
public prop Label: string => $"{Celsius:F1}°C";
public prop Kelvin: float => Celsius + 273.15;
public prop Fahrenheit: float
{
get => Celsius * 1.8 + 32.0;
set
{
Celsius = (value - 32.0) / 1.8;
}
}
}prop Celsius: float = 0.0;是自动属性:编译器配好背后的存储槽,初始化器给初值。- 表达式体
=> expr是只读的计算属性,每次读取现算。Kelvin就是只读的派生面。
显式访问器
读与写需要不同逻辑时,用 get / set 访问器:
public prop Fahrenheit: float
{
get => Celsius * 1.8 + 32.0;
set
{
Celsius = (value - 32.0) / 1.8;
}
}get / set 可以各自选择形态:;(自动)、=> 表达式、{ 块 }。set 体内 value 指写入的值。
set(value) 与背槽 field
setter 的值参数可以改名,改了名之后体内只有这个名字,value 不再注入。访问器体里的 field 关键字直指背后的存储槽,适合「读取时包装、写入时存原文」:
class Notebook
{
public prop Note: string
{
get => "读数 " + field;
set(n)
{
field = n;
}
} = "空";
}
val t = new Notebook();
t.Note = "偏高";
print(t.Note);读数 偏高= "空" 是初始化器,写在访问器块之后,属性读出来是 "读数 " + 存的值。
computed:派生读专用形态
computed prop 是「只读计算属性」的关键字形态,隐式 pure,专用于派生值,它是响应式计算属性:
class Reservoir
{
public prop Level: int = 5;
public computed prop Doubled: int => Level * 2;
public prop Status: string
{
get => $"液位 {Level}";
}
}
val r = new Reservoir();
print(r.Level, r.Doubled, r.Status);
r.Level = 9;
print(r.Doubled, r.Status);5 10 液位 5
18 液位 9Doubled 每次读取按 Level 现算,改 Level 后立即反映,见事件与响应部分。
虚派发:virtual prop 与 override prop
属性和方法一样走虚派发:基类标 virtual prop,派生类用 override prop 提供新实现,基类引用与协议位读到的都是运行时类型的版本:
class Package
{
public virtual prop Label: string => "普通件";
}
class Fresh : Package
{
public override prop Label: string => "冷链件";
}
val shelf = new list<Package>();
shelf.Add(new Package());
shelf.Add(new Fresh());
for p in shelf
{
print(p.Label);
}普通件
冷链件整套连起来
val t = new Thermometer();
print(t.Celsius, t.Fahrenheit, t.Label);
t.Fahrenheit = 212.0;
print(t.Celsius, t.Kelvin);0 32 0.0°C
100 373.15Fahrenheit 的 set 把华氏换算回摄氏存进 Celsius,get 再从 Celsius 现算,两个属性共享同一份真值。Kelvin 是只读的派生面。
注意
- 访问器体内避免高开销操作:属性读写的调用方应默认它是廉价操作。
最后更新于 2026年10月9日
