1

我正在构建一个 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;

这是正确的,还是有更好和最有效的方法来按名称检索任意按钮?

4

1 回答 1

1

我认为,如果您只有有限数量的按钮也没关系,速度应该没问题。

如果我有这种情况,我经常使用这样的解决方案:

var
  ButtonDict: TDictionary<String,TButton>;
  FoundButton: TButton;
begin

  ...

  ButtonDict.Add(UpperCase(Button1.Name),Button1);
  ButtonDict.Add(UpperCase(Button2.Name),Button2);
  ButtonDict.Add(UpperCase(Button3.Name),Button3);

  ... 

  //fast access...
  if ButtonDict.TryGetValue(UpperCase(NameOfButton),FoundButton) then
  begin
    //... now you got the button... 
  end else
  begin
    // Button not found...
  end;

  ...

end;
于 2017-05-09T21:33:32.407 回答