我希望创建一个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 Error] edGenerics.pas(106): E2010 不兼容的类型:'TCatalogueItem' and 'TIndexedObject'
然而,编译器在编译单元结束时(第106行)显示错误,而不是在声明本身处,这对我来说没有任何意义...
基本上,我的想法是,我有一个从TObjectList继承的通用列表,我可以根据需要扩展新功能。关于此问题的任何帮助都将非常重要!
我应该补充说明,使用Delphi 2010。
谢谢。
//错误发生在这里
或//这是第106行
这样的简单注释就足够了。 - Ken WhiteTIndexedObjectList<T: TIndexedObject>
不应该从TObjectList<T>
继承,而应该从TObjectBaseList<T: TObjectBase>
继承,这样更合适。 - ain