这个问题已经在这里有了答案: 9年前关闭。 我有一个收藏TList<TActivityCategory>TActivityCategory具有字符串类型的Name属性,我想使用Name属性搜索TList。我在TList 中看到BinarySearch,但这需要一个TActivityCategory实例。我只想将字符串作为名称传递。我将如何去做呢? (adsbygoogle = window.adsbygoogle || []).push({}); 最佳答案 创建列表时,您可以传递比较器。 Generics.Defaults单元中有一些比较器类,您可以在其中传递一些匿名方法来比较两个元素。它们用于多种方法,例如IndexOf,Contains或Sort。例子:uses Generics.Defaults, Generics.Collections;type TActivityCategory = class private FName: string; public constructor Create(const Name: string); property Name: string read FName write FName; end;constructor TActivityCategory.Create(const Name: string);begin FName := Name;end;procedure TForm1.Button1Click(Sender: TObject);var activities: TList<TActivityCategory>; search: TActivityCategory;begin activities := TObjectList<TActivityCategory>.Create( TDelegatedComparer<TActivityCategory>.Create( function(const Left, Right: TActivityCategory): Integer begin Result := CompareText(Left.Name, Right.Name); end)); activities.Add(TActivityCategory.Create('Category B')); activities.Add(TActivityCategory.Create('Category C')); activities.Add(TActivityCategory.Create('Category A')); search := TActivityCategory.Create('Category C'); if activities.Contains(search) then ShowMessage('found'); ShowMessageFmt('Index: %d', [activities.IndexOf(search)]); activities.Sort; ShowMessageFmt('Index: %d', [activities.IndexOf(search)]); search.Name := 'Category D'; if not activities.Contains(search) then ShowMessage('not found'); search.Free; activities.Free;end; (adsbygoogle = window.adsbygoogle || []).push({}); 10-08 01:29