delphi – 如何在派生类型中使用泛型方法
发布时间:2020-12-15 04:12:47 所属栏目:大数据 来源:网络整理
导读:这看起来相当简单,也许我只是缺少一些语法粘合…这是我的简单泛型(Delphi XE3)示例: unit Unit1;interfaceuses generics.collections;typeX = classpublic Id: Integer;end;XListT : X = class( TObjectListT ) function Find(Id: Integer) : T;end;Y = cla
这看起来相当简单,也许我只是缺少一些语法粘合…这是我的简单泛型(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以返回找到的项目并退出方法. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |