Delphi之参数化类型(泛型)

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也会具有这样的方便语法.

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值