这是由 Deltic 的回答提示的,我想提供一个反例来证明您可以在动物喂养程序中使用泛型。 (即:多态泛型列表)
首先是一些背景知识:您可以使用通用基列表类来喂养通用动物的原因是因为您通常会有这种继承:
TBaseList = class
// Some code to actually make this a list
end
TSpecificList = class(TBaseList)
// Code that reintroduces the Add and GetItem routines to turn TSpecificList
// into a type-safe list of a different type, compatible with the TBaseList
end
这不适用于泛型,因为您通常会有这样的:
TDogList = TList<TDog>
end
TCatList = TList<TCat>
end
... 这两个列表的唯一“共同祖先”是TObject - 一点帮助都没有。但是我们可以定义一个新的泛型列表类型,它接受两个类参数:TAnimal 和TSpecificAnimal,生成与TAnimal 的泛型列表兼容的TSpecificAnimal 类型安全列表。这是基本类型定义:
TCompatibleList<T1:class;T2:class> = class(TObjectList<T1>)
private
function GetItem(i: Integer): T2;
public
procedure Add(A:T2);
property Item[i:Integer]:T2 read GetItem;default;
end;
使用这个我们可以做到:
TAnimal = class;
TDog = class(TAnimal);
TCat = class(TAnimal);
TDogList = TCompatibleList<TAnimal, TDog>;
TCatList = TCompatibleList<TAnimal, TCat>;
这样 TDogList 和 TCatList 实际上都继承自 TObjectList<TAnimal>,所以我们现在有了一个多态的泛型列表!
这是一个完整的控制台应用程序,展示了这个概念的实际应用。该类现在正在进入我的 ClassLibrary 以供将来重用!
program Project23;
{$APPTYPE CONSOLE}
uses
SysUtils, Generics.Collections;
type
TAnimal = class
end;
TDog = class(TAnimal)
end;
TCat = class(TAnimal)
end;
TCompatibleList<T1:class;T2:class> = class(TObjectList<T1>)
private
function GetItem(i: Integer): T2;
public
procedure Add(A:T2);
property Item[i:Integer]:T2 read GetItem;default;
end;
{ TX<T1, T2> }
procedure TCompatibleList<T1, T2>.Add(A: T2);
begin
inherited Add(T1(TObject(A)));
end;
function TCompatibleList<T1, T2>.GetItem(i: Integer): T2;
begin
Result := T2(TObject(inherited Items[i]));
end;
procedure FeedTheAnimals(L: TObjectList<TAnimal>);
var A: TAnimal;
begin
for A in L do
Writeln('Feeding a ' + A.ClassName);
end;
var Dogs: TCompatibleList<TAnimal, TDog>;
Cats: TCompatibleList<TAnimal, TCat>;
Mixed: TObjectList<TAnimal>;
begin
try
// Feed some dogs
Dogs := TCompatibleList<TAnimal, TDog>.Create;
try
Dogs.Add(TDog.Create);
FeedTheAnimals(Dogs);
finally Dogs.Free;
end;
// Feed some cats
Cats := TCompatibleList<TAnimal, TCat>.Create;
try
Cats.Add(TCat.Create);
FeedTheAnimals(Cats);
finally Cats.Free;
end;
// Feed a mixed lot
Mixed := TObjectList<TAnimal>.Create;
try
Mixed.Add(TDog.Create);
Mixed.Add(TCat.Create);
FeedTheAnimals(Mixed);
finally Mixed.Free;
end;
Readln;
except
on E: Exception do
Writeln(E.ClassName, ': ', E.Message);
end;
end.