TObjectList查找Item

时间:2017-05-08 20:15:35

标签: firemonkey tobjectlist

我构建一个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中的Button名称进行比较,如

function TForm1.FindButton (const aButtonName: string; var aButton: tButton) : Boolean;

这是正确的,还是有一种更好,更有效的方式来检索任意按钮的名称?

1 个答案:

答案 0 :(得分: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;