delphi – 如何在派生类型中使用泛型方法

这看起来相当简单,也许我只是缺少一些语法粘合…这是我的简单泛型(Delphi XE3)示例:
unit Unit1;

interface

uses
  generics.collections;

type

X = class
public
  Id: Integer;
end;

XList<T : X> = class( TObjectList<T> )
 function Find(Id: Integer) : T;
end;

Y = class(X)

end;

YList = class(XList<Y>)
end;

implementation

{ XList<T> }

function XList<T>.Find(Id: Integer): T;
var
  t: X;
begin
  for t in Self do
    if t.Id = Id then
      Result := t;
end;

end.

这不会用“[dcc32错误] Unit1.pas(41)编译:E2010不兼容的类型:’Y’和’X’”.这是下线:

YList = class(XList<Y>)
end;

Y来自X,为什么会出现问题?

解决方法

我必须按如下方式重新实现Find方法来修复它:
{ XList<T> }

function XList<T>.Find(Id: Integer): T;
var
  item: T;
begin
  for item in Self do
    if item.Id = Id then
      Exit(item);
  Result := nil;
end;

这里最重要的是将变量声明中使用的类型从X替换为T.

然后我只是将变量从t重命名为item以避免与类型占位符T发生名称冲突,并通过Exit(item)替换Result:= item以返回找到的项目并退出方法.

相关文章

 从网上看到《Delphi API HOOK完全说明》这篇文章,基本上都...
  从网上看到《Delphi API HOOK完全说明》这篇文章,基本上...
ffmpeg 是一套强大的开源的多媒体库 一般都是用 c/c+&#x...
32位CPU所含有的寄存器有:4个数据寄存器(EAX、EBX、ECX和ED...
1 mov dst, src dst是目的操作数,src是源操作数,指令实现的...