我需要一个实现接口且不使用引用计数的类。我按照以下方式进行操作:
缺少引用计数是可以正常工作的。但我担心的是,我无法使用
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 Error] E2015运算符不适用于此操作数类型
当 TMyClass
从 TInterfacedObject
派生时,该问题会消失——也就是说,我可以进行这种转换而没有编译器错误。显然,我不想使用 TInterfacedObject 作为基类,因为这将使我的类引用计数。为什么这样的转换被禁止,如何解决呢?
as
、GetInterface
和supports
等需要能够通过 GUID 识别接口才能正常工作。 - Marjan Venema