【发布时间】:2013-02-02 15:01:42
【问题描述】:
我需要一个没有引用计数的类实现接口。我做了以下事情:
IMyInterface = interface(IInterface)
['{B84904DF-9E8A-46E0-98E4-498BF03C2819}']
procedure InterfaceMethod;
end;
TMyClass = class(TObject, IMyInterface)
protected
function _AddRef: Integer;stdcall;
function _Release: Integer;stdcall;
function QueryInterface(const IID: TGUID; out Obj): HResult;stdcall;
public
procedure InterfaceMethod;
end;
procedure TMyClass.InterfaceMethod;
begin
ShowMessage('The Method');
end;
function TMyClass.QueryInterface(const IID: TGUID; out Obj): HResult;
begin
if GetInterface(IID, Obj) then
Result := 0
else
Result := E_NOINTERFACE;
end;
function TMyClass._AddRef: Integer;
begin
Result := -1;
end;
function TMyClass._Release: Integer;
begin
Result := -1;
end;
缺少引用计数可以正常工作。但我担心的是我不能使用as 运算符将TMyClass 转换为IMyInterface:
var
MyI: IMyInterface;
begin
MyI := TMyClass.Create as IMyInterface;
给我
[DCC 错误] E2015 运算符不适用于此操作数类型
当TMyClass 派生自TInterfacedObject 时,问题就消失了——也就是说,我可以在没有编译器错误的情况下进行这种转换。显然我不想使用 TInterfacedObject 作为基类,因为它会使我的类引用计数。为什么不允许这种强制转换以及如何解决它?
【问题讨论】:
-
在接口声明中添加 GUID 可能会获得更好的结果。在
= interface行之后添加一个新行,然后按 Ctrl-Shft-G。as、GetInterface和supports等需要能够通过GUID识别接口才能工作。 -
你没有仔细阅读我的帖子。当我从 TInterfacedObject 派生时,它可以工作。 GUID 与这里无关。您只需要 GUID 即可使用 COM。
-
嗯,哪个 Delphi 版本?
-
不,您不仅需要 GUID 来使用 COM。您需要 GUID 才能在许多方面使用接口。您是否尝试过添加 GUID 并查看会发生什么?
-
@DavidHeffernan 在将 IInterface 添加到它的工作列表后。您能否发布一个答案,以便我可以通过一些解释接受它?
标签: delphi interface delphi-xe2