我正在构建一个 TObjectList,它将存储类 tButton 的对象:
...
type
TForm1 = class(TForm)
Button1: TButton;
Button2: TButton;
Button3: TButton;
procedure FormCreate(Sender: TObject);
public
function FindButton (const aButtonName: string; var aButton: tButton) : Boolean;
end;
...
var ButtonObjectList : TObjectList<TButton>;
function TForm1.FindButton (const aButtonName: string; var aButton: tButton) : Boolean;
...
var b : Integer;
begin
Result := False;
for b := Low (ButtonObjectList.Count) to High (ButtonObjectList.Count) do
if ButtonObjectList.Items [b].Name = aButtonName then begin
Result := True;
aButton := ButtonObjectList.Items [b];
end;
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
ButtonObjectList := TObjectList<TButton>.Create(True);
ButtonObjectList.Add(Button1);
ButtonObjectList.Add(Button2);
ButtonObjectList.Add(Button3);
end;
此外,在单元 untRetrieveButton 中:
...
var Button : TButton;
procedure FindAButton;
begin
if Form1.FindButton ('Button 1', Button) then
ShowMessage ('Button found')
else
ShowMessage ('Button not found')
end;
我想取回存储在 ButtonObjectList 中的任意按钮,但此时我只知道按钮的名称。根据我在 TObjectList 文档中学到的内容,实现此目的的唯一方法是遍历整个 Items 列表,并将参数 aButtonName 与 TObjectList 中的按钮名称进行比较,如
function TForm1.FindButton (const aButtonName: string; var aButton: tButton) : Boolean;
这是正确的,还是有更好和最有效的方法来按名称检索任意按钮?