我需要一個實現沒有引用計數接口的類。我做了以下操作:將對象轉換爲沒有TInterfacedObject作爲基類的接口類型
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識別接口才能工作。 – 2013-02-18 08:21:31
您沒有仔細閱讀我的文章。當我從TInterfacedObject派生它的作品。 GUID在這裏沒有任何關係。您只需要使用GUID來使用COM。 – 2013-02-18 08:23:36
嗯,哪個Delphi版本? – 2013-02-18 08:24:58