一般来说,我们定义接口都会同时为接口定义一个GUID值,以便能够能够通过 QueryInterface 或 Supports 等函数来进行接口间的转换。但如果一个未定义接口ID的接口,QueryInterface/Supports 由于都需要接口 GUID, 许多时候就无能为力了。
对于这种情况,实际上我们可以通过将接口转换为接口实现的类,然后再赋值给目标来解决。示例如下:
type
INoIdInterface=interface
function GetId:Integer;
end;
TNoIdObject=class(TInterfacedObject,INoIdInterface)
...
end;
function GetNoIdInterface(const AIntf:IInterface):INoIdInterface;
var
AObj:TObject;
begin
AObj:= AIntf as TObject;
if AObj is TNoIdObject then
Result:=TNoIdObject(AObj)
else
Result:=nil;
end;
本质上找到其声明的类型,然后再转换成对应的类型再赋给接口对象来解决。
当然,如果 TNoIdObject 并没有在 interface 里找到,那么我们就需要额外的技巧,有兴趣的可以自行研究下。
