说我有一个基类:
TPart = class
private
FPartId: Integer;
public
property PartId: Integer read FPartId write FPartId;
end;
我有一个通用列表:
TPartList = class(TObjectList<TPart>)
public
function IndexOfPart(PartId: Integer): Integer;
end;
现在,如果我从我的TPart下来:
TModulePart = class(TPart)
private
FQuantity: Integer;
public
property Quantity: Integer read FQuantity write FQuantity;
end;
我想现在创建一个TPartList的后代,但能够返回一个TModulePart项。这样做:
TModulePartList = class(TPartList)
end;
默认情况下会认为Items属性是TPart类型而不是TModulePart(自然)。我不想这样做:
TModulePartList = class(TObjectList<TModulePart>)
end;
因为那时我错过了从TPartList中可能有的常用方法继承。
有可能吗?
由于
答案 0 :(得分:3)
你可以这样做你想做的事:
TGenericPartList<T: TPart> = class(TObjectList<T>)
public
function IndexOfPart(PartId: Integer): Integer;
end;
TPartList = TGenericPartList<TPart>;
TModulePartList = TGenericPartList<TModule>;
如果你这样设计,你可以增加更多的灵活性:
TGenericPartList<T: TPart> = class(TObjectList<T>)
public
function IndexOfPart(PartId: Integer): Integer;
end;
TPartList = TGenericPartList<TPart>;
TGenericModulePartList<T: TModule> = class(TGenericPartList<T>)
procedure DoSomething(Module: T);
end;
TModulePartList = TGenericModulePartList<TModule>;