Pet*_*erS 7 delphi generics interface delphi-2010
鉴于下面的代码,这是一个非常精简的实际代码版本,我收到以下错误:
[DCC错误] Unit3.pas(31):E2010不兼容类型:'IXList <Unit3.TXList <T> .FindAll.S>'和'TXList <Unit3.TXList <T> .FindAll.S>'
在FindAll <S>函数中.
我真的不明白为什么因为以前很相似的功能没有问题.
任何人都可以对此有所了解吗?
是我还是编译器中的错误?
单位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.
Run Code Online (Sandbox Code Playgroud)
谢谢你的回答!它似乎是一个可用的可接受解决方案的编译器错误.
将接口声明为
IXList<T: class> = interface
function GetEnumerator: TList<T>.TEnumerator;
end;
Run Code Online (Sandbox Code Playgroud)
并且findall实现为
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;
Run Code Online (Sandbox Code Playgroud)
我让它在一个简单的例子中工作.
做类似的事情:
var
l: TXList<TAClass>;
i: TASubclassOfTAClass;
begin
.
.
.
for i in l.FindAll<TASubclassOfTAClass> do
begin
// Do something with i
end;
Run Code Online (Sandbox Code Playgroud)
通过三个小修改(IInterface,FindAll with"S:class"[Thanks Mason]和FindAll中的类型转换)我得到了它的编译.
完整代码:
unit Unit16;
interface
uses
Generics.Collections;
type
IXList<T> = interface
end;
TXList<T: class> = class(TList<T>, IInterface, 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: class>: 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 := IXList<S>(IUnknown(TXList<S>.Create));
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.
Run Code Online (Sandbox Code Playgroud)