我一直在想接口作为一种方式来给不同的不相关的类一个共同的功能。但接口的属性 - “RefCOunt下降到零时释放一个对象”不允许我按照我的想法工作。如何解决接口混乱
例如:让我们假设我有两个不同的类:TMyObject和TMyDifferentObject。他们都支持此接口:现在
const
IID_MyInterface: TGUID = '{4D91C27F-510D-4673-8773-5D0569DFD168}';
type
IMyInterface = Interface(IInterface)
['{4D91C27F-510D-4673-8773-5D0569DFD168}']
function GetID : Integer;
end;
type
TMyObject = class(TInterfacedObject, IMyInterface)
function GetID: Integer;
end;
function TMyObject.GetID: Integer;
begin
Result := 1;
end;
type
TMyDifferentObject = class(TInterfacedObject, IMyInterface)
function GetID: Integer;
end;
function TMyDifferentObject.GetID: Integer;
begin
Result := 2;
end;
,我想在我的程序来创建这个类的实例,然后通过这些实例,以这种方法:
procedure ShowObjectID(AObject: TObject);
var
MyInterface: IMyInterface;
begin
if Supports(AObject, IID_MyInterface, MyInterface) then
begin
ShowMessage(IntToStr(MyInterface.GetID));
end;
end; //Interface goes out of scope and AObject is freed but I still want to work with that object!
这是一个例子。一般来说,我想通过一些过程传递对象的实例,并检查该对象是否支持接口,如果是,我想执行此接口的方法。但是当接口超出范围时,我不想完成那个对象的工作。这个怎么做?
问候。
您可以禁用引用计数。看看IInterface是如何在TComponent中实现的。 –