这似乎很简单,也许我只是缺少一些语法胶水。这是我简单的通用(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;
What's这里重要的是,以取代从变量声明中使用的类型X
来T
。
然后,我只是改名从变量t
,以item
避免名称冲突与类型占位符T
和raplaced将Result := item
通过Exit(item)
返回找到的项目和退出方法。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句