我需要一个没有引用计数的类实现接口。我做了以下工作:
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运算符将IMyInterface转换为as:
var
MyI: IMyInterface;
begin
MyI := TMyClass.Create as IMyInterface;我被赐予
不适用于此操作数类型的DCC错误E2015运算符
当TMyClass从TInterfacedObject派生出来时,这个问题就消失了--也就是说,我可以在没有编译器错误的情况下进行这样的转换。显然,我不想使用TInterfacedObject作为基类,因为它会使我的类引用计算在内。为什么这样的演员是不被允许的,如何解决这个问题呢?
发布于 2013-02-18 08:32:30
您不能在代码中使用as的原因是您的类没有在其支持的接口列表中显式地列出IInterface。即使您的接口来自IInterface,除非您实际列出了该接口,否则您的类不支持它。
因此,简单的解决方法是像这样声明类:
TMyClass = class(TObject, IInterface, IMyInterface)类需要实现IInterface的原因是编译器依赖于实现as强制转换。
我想指出的另一点是,一般来说,您应该避免使用接口继承。总的来说,它并没有什么用处。使用接口的好处之一是您不受实现继承带来的单一继承约束的影响。
但是在任何情况下,所有的Delphi接口都是IInterface的,所以在您的例子中,没有必要指定它。我会像这样声明你的界面:
IMyInterface = interface
['{B84904DF-9E8A-46E0-98E4-498BF03C2819}']
procedure InterfaceMethod;
end;更广泛地说,您应该努力避免在接口中使用继承。通过采用这种方法,您将鼓励更少的耦合,从而带来更大的灵活性。
https://stackoverflow.com/questions/14931940
复制相似问题