【发布时间】:2013-02-06 05:21:10
【问题描述】:
我想创建一个TObjectList<T> 后代来处理我的应用程序中对象列表之间的通用功能。然后我想从那个新类中进一步下降,以便在需要时引入额外的功能。我似乎无法使用超过 1 级的继承来使其工作。我可能需要更多地了解泛型,但我一直在寻找正确的方法来做到这一点,但没有成功。到目前为止,这是我的代码:
unit edGenerics;
interface
uses
Generics.Collections;
type
TObjectBase = class
public
procedure SomeBaseFunction;
end;
TObjectBaseList<T: TObjectBase> = class(TObjectList<T>)
public
procedure SomeOtherBaseFunction;
end;
TIndexedObject = class(TObjectBase)
protected
FIndex: Integer;
public
property Index: Integer read FIndex write FIndex;
end;
TIndexedObjectList<T: TIndexedObject> = class(TObjectBaseList<T>)
private
function GetNextAutoIndex: Integer;
public
function Add(AObject: T): Integer;
function ItemByIndex(AIndex: Integer): T;
procedure Insert(AIndex: Integer; AObject: T);
end;
TCatalogueItem = class(TIndexedObject)
private
FID: integer;
public
property ID: integer read FId write FId;
end;
TCatalogueItemList = class(TIndexedObjectList<TCatalogueItem>)
public
function GetRowById(AId: Integer): Integer;
end;
implementation
uses
Math;
{ TObjectBase }
procedure TObjectBase.SomeBaseFunction;
begin
end;
{ TObjectBaseList<T> }
procedure TObjectBaseList<T>.SomeOtherBaseFunction;
begin
end;
{ TIndexedObjectList }
function TIndexedObjectList<T>.Add(AObject: T): Integer;
begin
AObject.Index := GetNextAutoIndex;
Result := inherited Add(AObject);
end;
procedure TIndexedObjectList<T>.Insert(AIndex: Integer; AObject: T);
begin
AObject.Index := GetNextAutoIndex;
inherited Insert(AIndex, AObject);
end;
function TIndexedObjectList<T>.ItemByIndex(AIndex: Integer): T;
var
I: Integer;
begin
Result := Default(T);
while (Count > 0) and (I < Count) and (Result = Default(T)) do
if Items[I].Index = AIndex then
Result := Items[I]
else
Inc(I);
end;
function TIndexedObjectList<T>.GetNextAutoIndex: Integer;
var
I: Integer;
begin
Result := 0;
for I := 0 to Count - 1 do
Result := Max(Result, Items[I].Index);
Inc(Result);
end;
{ TCatalogueItemList }
function TCatalogueItemList.GetRowById(AId: Integer): Integer;
var
I: Integer;
begin
Result := -1;
for I := 0 to Pred(Self.Count) do
if Self.Items[I].Id = AId then
begin
Result := I;
Break;
end;
end;
end.
/////// ERROR HAPPENS HERE ////// ???? why is beyond me
似乎有以下声明:
>>> TCatalogueItemList = class(TIndexedObjectList<TCatalogueItem>) <<<<
导致以下编译器错误:
[DCC 错误] edGenerics.pas(106): E2010 不兼容的类型: 'TCatalogueItem' 和 'TIndexedObject'
但是编译器在编译单元的 END 处(第 106 行)显示错误,而不是在声明本身上,这对我来说没有任何意义......
基本上我的想法是我有一个从 TObjectList 下降的通用列表,我可以根据需要使用新功能进行扩展。对此的任何帮助都会很棒!!!
我应该使用 Delphi 2010 添加。
谢谢。
【问题讨论】:
-
如果您能指出导致错误的代码的实际部分,那就太好了(因为您可以使用它)。这比期望我们计算或复制/粘贴到编辑器中要容易得多。像
// error happens here或//this is line 106这样的简单评论就足够了。 -
对问题正文添加了进一步的解释
-
不应该
TIndexedObjectList<T: TIndexedObject>从TObjectBaseList<T: TObjectBase>下降而不是TObjectList<T>在您当前的代码中? -
是的,应该感谢您接受它。但是在对声明进行更正后,它与之前的编译错误完全相同。
-
@Ken:XE3 IDE 将错误定位在文件的最后一行(最后结束之后)。错误消息中没有提供行号。
标签: delphi generics delphi-2010