Delphi中的ObjectList简单用法一则

      最近项目中需要搞很多个同一类对象的管理和操作,我居然还想用数组array来实现。在当当的教育下,开始研究TObjectList。Delphi中将一系列对象进行数组形式的维护,TObjectList是一个不错的实现方法。他帮助我们添加、计数、删除、释放一个List列表中的内容。
  基本实现不难,自己做一个类,把对象数组像List一样封装到Items中去,然后根据需要实现一些需要的Add/ Count/ Remove/ Clear等操作。实现很简单,直接调用ObjectList的固有函数即可。一个实现的伪代码的例子如下。(修改自最近的Project文件,维护一个TMyClass类的实例列表)Blogbus没有语法高亮功能,很是让人郁闷。

TReminder = class(TPersistent)
private
  FFileName: 
string;
  FItems: TObjectList;
  
function ReadItems(Index: Integer): TMyClass;
  
procedure SetItems(Index: Integer; const Value: TMyClass);
public
  
property Items[Index: Integer]: TMyClass read ReadItems write SetItems;
  
function Add(MyClass: TMyClass): Integer;
  
function Count(): Integer;
  
constructor Create;
end;

implementation

function TReminder.Add(MyClass: TMyClass): Integer;
begin
  Result :
= FItems.Add(MyClass);
end;

function TReminder.Count: Integer;
begin
  Result :
= FItems.Count;
end;

constructor TReminder.Create;
begin
  
inherited;
  FItems :
= TObjectList.Create;

end;

function TReminder.ReadItems(Index: Integer): TMyClass;
begin
  Result :
= TMyClass(FItems[Index]);
end;

procedure TReminder.SetItems(Index: Integer; const Value: TMyClass);
begin
  FItems[Index] :
= Value;
end;
原文地址:https://www.cnblogs.com/innwin/p/1415114.html