我需要一个像TInterfacedObject这样的基类,但是没有引用计数(所以是一种TNonRefCountedInterfacedObject)。
这实际上是我第n次需要这样的类,不知何故,我总是一次又一次地编写(读取:复制和粘贴)我自己的类。我不敢相信我没有可以使用的“官方”基类。
在实现IInterface的RTL中有没有一个基类,但是没有引用计数,我可以从中派生我的类?
发布于 2011-08-17 00:41:22
在单元Generics.Defaults中,定义了一个类TSingletonImplementation。在Delphi 2009及更高版本中可用。
// A non-reference-counted IInterface implementation.
TSingletonImplementation = class(TObject, IInterface)
protected
function QueryInterface(const IID: TGUID; out Obj): HResult; stdcall;
function _AddRef: Integer; stdcall;
function _Release: Integer; stdcall;
end;发布于 2011-08-16 23:11:19
这是我干的。它可以使用或不使用引用计数来代替TInterfacedObject。它还有一个name属性--在调试时非常有用。
// TArtInterfacedObject
// =============================================================================
// An object that supports interfaces, allowing naming and optional reference counting
type
TArtInterfacedObject = class( TInterfacedObject )
constructor Create( AReferenceCounted : boolean = True);
PRIVATE
FName : string;
FReferenceCounted : boolean;
PROTECTED
procedure SetName( const AName : string ); virtual;
PUBLIC
property Name : string
read FName
write SetName;
function QueryInterface(const AGUID : TGUID; out Obj): HResult; stdcall;
function SupportsInterface( const AGUID : TGUID ) : boolean;
function _AddRef: Integer; stdcall;
function _Release: Integer; stdcall;
end;
// =============================================================================
{ TArtInterfacedObject }
constructor TArtInterfacedObject.Create( AReferenceCounted : boolean = True);
begin
inherited Create;
FName := '';
FReferenceCounted := AReferenceCounted;
end;
function TArtInterfacedObject.QueryInterface(const AGUID: TGUID; out Obj): HResult;
const
E_NOINTERFACE = HResult($80004002);
begin
If FReferenceCounted then
Result := inherited QueryInterface( AGUID, Obj )
else
if GetInterface(AGUID, Obj) then Result := 0 else Result := E_NOINTERFACE;
end;
procedure TArtInterfacedObject.SetName(const AName: string);
begin
FName := AName;
end;
function TArtInterfacedObject.SupportsInterface(
const AGUID: TGUID): boolean;
var
P : TObject;
begin
Result := QueryInterface( AGUID, P ) = S_OK;
end;
function TArtInterfacedObject._AddRef: Integer;
begin
If FReferenceCounted then
Result := inherited _AddRef
else
Result := -1 // -1 indicates no reference counting is taking place
end;
function TArtInterfacedObject._Release: Integer;
begin
If FReferenceCounted then
Result := inherited _Release
else
Result := -1 // -1 indicates no reference counting is taking place
end;
// =============================================================================发布于 2011-08-16 23:17:36
你可以考虑使用TInterfacedPersistent。如果你不覆盖GetOwner,它就不会进行引用计数。
https://stackoverflow.com/questions/7080178
复制相似问题