gpt4 book ai didi

delphi - Delphi 2010 中返回泛型接口(interface)的泛型方法

转载 作者:行者123 更新时间:2023-12-03 14:52:50 25 4
gpt4 key购买 nike

鉴于下面的代码(这是实际代码的非常精简的版本),我收到以下错误:

[DCC 错误] Unit3.pas(31): E2010 不兼容的类型:'IXList .FindAll.S>' 和 'TXList .FindAll.S>'

在 FindAll 函数中。

我真的不明白为什么,因为之前非常相似的功能没有问题。

有人能解释一下吗?
是我的问题还是编译器的错误?

单元3;

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.

谢谢各位的解答!这似乎是一个编译器错误,有一个可接受的解决方法。

接口(interface)声明为

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、带有“S: class”的 FindAll [感谢 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.

关于delphi - Delphi 2010 中返回泛型接口(interface)的泛型方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3574358/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com