Delphi做容器比较不方便的地方就是没有泛型,也就是参数化类型.
例如TList里面每一项是TForm.那么Delphi就不能使用List[I].Show();这样的方法.而必须做类型转换.
TForm(List[I]).Show();
虽说一样能实现,但是毕竟麻烦.C++正是因为支持泛型才有的模板库.
Rad Studi 2007的Delphi.NET已经开始支持泛型了.这个我不太感兴趣,我感兴趣的是Delphi Win32对泛型的支持.
根据Code Gear发布的Delphi路线图.Delphi Win32在2008上半年发行的版本里会支持泛型.
不过我们到时可以用Delphi2007.NET先预览一下Delphi对泛型的语法支持是怎样的.
查了一下CodeGear上面的官方说法.不过给出的例子语法很多地方都不对.自己琢磨了很久才出正确的.CodeGear这态度太"认真"了.
type
TGenericList <T> = class
private
FData : array of T;
function GetItem(Index: Integer): T;
public
Function Add(Item : T):Integer;
function GetCount: Integer;
procedure Delete();
Procedure Clear();
property Count : Integer Read GetCount;
property Item[Index : Integer] : T read GetItem;default;
end;
function TGenericList<T>.Add(Item: T): Integer;
begin
Result := Count;
SetLength(FData, Result + 1);
FData[Result] := Item;
end;
procedure TGenericList<T>.Clear;
begin
//懒得写了
end;
procedure TGenericList<T>.Delete;
begin
//懒得写了
end;
function TGenericList<T>.GetCount: Integer;
begin
Result := 0;
if FData = nil then
Exit;
Result := Length(FData);
end;
function TGenericList<T>.GetItem(Index: Integer): T;
begin
Result := FData[Index];
end;
使用的时候
var
ButtonList : TGenericList<TButton>;
I : Integer;
begin
ButtonList := TGenericList<TButton>.Create();
for I := 0 to 3 do
begin
ButtonList.Add(TButton.Create(Self));
ButtonList[I].Caption := IntToStr(I);
ButtonList[I].Top := ButtonList[I].Height*I;
ButtonList[I].Parent := Self;
end;
ButtonList.Free();
end;
至于Delphi的泛型是像C++,Java那样基于源代码替换机制还是像.NET那样的基于运行时信息的我就没有细看.毕竟我对IL ASM不是特别熟悉.估计Delphi.NET可能是和C#一样基于运行时吧.那么Delphi Win32呢?难道也是基于运行时?毕竟这样的话还要添加一些运行时的信息.如果是基于源码替换规则,那么DCU文件还要重新编译吗?毕竟C++的泛型OBJ,LIB文件不用编译,因为它有带源代码的头文件.不去想了
呵呵,在登上几个月.2008年上半年发布的Delphi for Win32也会具有这样的方便语法.