鉴于下面的代码,这是一个非常精简的实际代码版本,我收到以下错误:
[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.
谢谢你的答案!
它似乎是一个可用的可接受解决方案的编译器错误.
将接口声明为
IXList<T: class> = interface function GetEnumerator: TList<T>.TEnumerator; end;
并且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;
我让它在一个简单的例子中工作.
做类似的事情:
var l: TXList<TAClass>; i: TASubclassOfTAClass; begin . . . for i in l.FindAll<TASubclassOfTAClass> do begin // Do something with i end;
解决方法
通过三个小修改(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.