我需要一个没有引用计数的实现接口的类。我做了以下事情:
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;
缺乏引用计数效果很好。但我担心的是我无法投射TMyClass
to IMyInterface
using as
操作员:
var
MyI: IMyInterface;
begin
MyI := TMyClass.Create as IMyInterface;
我被给予
[DCC 错误] E2015 运算符不适用于此操作数类型
当TMyClass
源自于TInterfacedObject
- 即我可以进行这样的转换而不会出现编译器错误。显然我不想使用 TInterfacedObject 作为基类,因为它会使我的类引用计数。为什么不允许这样的转换以及如何解决它?
无法使用的原因as
在您的代码中,您的类没有明确列出IInterface
在其支持的接口列表中。即使您的界面源自IInterface
,除非您实际列出该接口,否则您的类不支持它。
因此,最简单的解决方法是像这样声明您的类:
TMyClass = class(TObject, IInterface, IMyInterface)
您的班级需要实施的原因IInterface
这就是编译器所依赖的来实现as
cast.
我想指出的另一点是,一般来说,您应该避免使用接口继承。总的来说,它没什么用处。使用接口的好处之一是您可以摆脱实现继承带来的单一继承约束。
但无论如何,所有Delphi接口自动继承自IInterface http://docwiki.embarcadero.com/RADStudio/en/Object_Interfaces#IInterface_and_Inheritance所以在你的情况下没有必要指定这一点。我会这样声明你的界面:
IMyInterface = interface
['{B84904DF-9E8A-46E0-98E4-498BF03C2819}']
procedure InterfaceMethod;
end;
更广泛地说,您应该尽量不要在接口中使用继承。通过采用这种方法,您将减少耦合,从而带来更大的灵活性。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)