本文介绍了Delphi:如何使用TObjectList< T>?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要了解如何使用通用Delphi 2009 TObjectList 。我的非 TObjectList 尝试看起来像

I need to understand how to use the generic Delphi 2009 TObjectList. My non-TObjectList attempt looked like

TSomeClass = class(TObject)
private
  FList1: Array of TList1;
  FList2: Array of TList2;
public
  procedure FillArray(var List: Array of TList1; Source: TSource); Overload;
  procedure FillArray(var List: Array of TList2; Source: TSource); Overload;
end;

这里, TList1 TList2 继承相同的构造函数构造函数TParent.Create(Key:string; Value:string); 。然而,由于不同的专业化(例如不同的专用领域),它们将不是相同的类型。所以我必须写两个几乎相同的填充方法:

Here, TList1 and TList2 inherits the same constructor constructor TParent.Create(Key: string; Value: string);. However, due to different specialization (e.g. different private fields), they will not be of the same type. So I have to write two nearly identical fill methods:

procedure TSomeClass.FillArray(var List: Array of TList1; Source: TSource);
begin
  for i := 0 to Source.List1.Count - 1 do begin
    SetLength(List, Length(List) + 1);
    List[i] := TList1.Create(Source.List1[i].Key, Source.List1[i].Value);
  end;
end;

FillArray(List:TList2的数组;源:TSource); 是完全相同的,除了用 TList2 替换 TList1 。据我所知,这可以通过使用 TObjectList 和单个填充方法整齐地规避;但是,我不知道如何去做这个。有人有一些很好的指点吗?谢谢!

with FillArray(List: Array of TList2; Source: TSource); being identical, except for the replacement of TList1 with TList2 throughout. As far as I understand, this could be neatly circumvented by using TObjectList and a single fill method; yet, I don't have a clue how to go about this. Do anyone have some good pointers on this? Thanks!

推荐答案

您将无法通过使用通用列表来缩减,因为通用类型是类定义。因此,一个 TObjectList< TMyClass1> TObjectList< TMyClass2> 不同(并且不兼容)。使用通用列表超过正常TList / TObjectList的主要好处是改进了类型安全性,较少的转换和更清晰的代码。

You wouldn't be able to condense that down by using a generic list, since a generic's type is part of the class definition. So a TObjectList<TMyClass1> is different from (and incompatible with) a TObjectList<TMyClass2>. The main benefit of using generic lists over normal TList/TObjectList is improved type safety, with less casts and cleaner code.

此外,如果您使用键/值对,你把它们放在列表中,然后通过搜索一个键并返回相关的值来检索它们?如果是这样的话,可以看一下在Genericics.Collections中的TDictionary。它是一个通用的键/值哈希表,可以为您大大简化此过程。

Also, if you're using key/value pairs, are you putting them into a list and then retrieving them by searching for a key and returning the associated value? If so, take a look at TDictionary in Generics.Collections. It's a generic key/value hash table that will greatly simplify this process for you.

这篇关于Delphi:如何使用TObjectList&lt; T&gt;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-17 20:00