Método genérico retornando interface genérica no Delphi 2010
Dado o código abaixo, que é uma versão muito reduzida do código real, recebo o seguinte erro:
[Erro DCC] Unit3.pas (31): E2010 Tipos incompatíveis: 'IXList <Unit3.TXList <T> .FindAll.S>' e 'TXList <Unit3.TXList <T> .FindAll.S>'
Na função FindAll <S>.
Eu realmente não consigo entender o porquê, pois não há nenhum problema com a função muito semelhante anterior.
Alguém pode lançar alguma luz sobre isso?
Sou eu ou é um bug no compilador?
unidade Unit3;
interface
uses Generics.Collections;
type
IXList<T> = interface
end;
TXList<T: class> = class(TList<T>, IXList<T>)
protected
FRefCount: Integer;
function QueryInterface(const IID: TGUID; out Obj): HResult; stdcall;
function _AddRef: Integer; stdcall;
function _Release: Integer; stdcall;
public
function Find: IXList<T>;
function FindAll<S>: IXList<S>;
end;
implementation
uses Windows;
function TXList<T>.Find: IXList<T>;
begin
Result := TXList<T>.Create;
end;
function TXList<T>.FindAll<S>: IXList<S>;
begin
Result := TXList<S>.Create; // Error here
end;
function TXList<T>.QueryInterface(const IID: TGUID; out Obj): HResult;
begin
Result := E_NoInterface;
end;
function TXList<T>._AddRef: Integer;
begin
InterlockedIncrement(FRefCount);
end;
function TXList<T>._Release: Integer;
begin
InterlockedDecrement(FRefCount);
if FRefCount = 0 then Self.Destroy;
end;
end.
Obrigado pelas respostas! Parece um bug do compilador com uma solução aceitável disponível.
Com a interface declarada como
IXList<T: class> = interface
function GetEnumerator: TList<T>.TEnumerator;
end;
e tudo implementado como
function TXList<T>.FindAll<S>: IXList<S>;
var
lst: TXList<S>;
i: T;
begin
lst := TXList<S>.Create;
for i in Self do
if i.InheritsFrom(S) then lst.Add(S(TObject(i)));
Result := IXList<S>(IUnknown(lst));
end;
Eu consegui trabalhar em um exemplo simples.
Fazendo algo como:
var
l: TXList<TAClass>;
i: TASubclassOfTAClass;
begin
.
.
.
for i in l.FindAll<TASubclassOfTAClass> do
begin
// Do something with i
end;