10.1.6 使用数组属性
属性一般让你访问单个值,甚至是复杂数据类型的值,但是Object Pascal语言也支持数组属性,或C#语言所说的索引器。数组属性是一种带有附加参数的属性,附加参数可以是用作索引的任何数据类型,或者(更常见的)是实际值的选择器。下面是一个使用整数索引并指向整数值的数组属性定义示例:
private
function GetValue(I: Integer): Integer;
procedure SetValue(I: Integer; const Value: Integer);
public
property Value[I: Integer]: Integer read GetValue write SetValue;
数组属性必须要映射到读和写的方法,读和写方法要有一个额外的参数表示索引。类似普通属性,您可以使用IDE的代码完成来定义方法。
值和索引有多种组合,RTL 中的一些类大量使用了数组属性。例如,TStrings 类定义了五种数组属性:
property Names[Index: Integer]: string read GetName;
property Objects[Index: Integer]: TObject read GetObject write PutObject;
property Values[const Name: string]: string read GetValue write SetValue;
property ValueFromIndex[Index: Integer]: string read GetValueFromIndex write SetValueFromIndex;
property Strings[Index: Integer]: string read Get write Put; default;
这些数组属性大多使用字符串的索引作为列表中的参数,而其他属性则使用字符串作为查找或搜索值(如上文的 Values 属性)。
最后一个定义使用了另一个重要特性:default关键字。这是一个强大的语法助手:数组属性的名称可以省略,这样就可以将方括号运算符直接应用于相关对象。
因此,如果你有一个 TStrings 类型的对象 SList,下面的两条语句都将起作用:
SList.Strings[1]
SList[1]
换句话说,默认数组属性提供了一种为任何对象定义自定义 [ ] 操作符的方法。