在记录中包装TStringList

HMc*_*McG 4 delphi records tstringlist

我倾向于使用Delphi的TStringList进行文本操作,所以我写了很多程序/函数,如:

var
  TempList: TStringList;
begin
  TempList:= TStringList.Create;
  try
    // blah blah blah do stuff with TempList   


  finally
    TempList.Free;
  end;
end;
Run Code Online (Sandbox Code Playgroud)

切断创建和释放这样一个常见的实用程序类会很好.

因为我们现在有方法的记录,是否可以在记录中包装类似TStringList的类,所以我可以:

var
  TempList: TRecordStringList;
begin
  // blah blah blah do stuff with TempList   


end;
Run Code Online (Sandbox Code Playgroud)

Bar*_*lly 15

这是可能的.创建一个公开所需方法/对象的接口:

type
  IStringList = interface
    procedure Add(const s: string); // etc.
    property StringList: TStringList read GetStringList; // etc.
  end;
Run Code Online (Sandbox Code Playgroud)

实现接口,让它包装真实TStringList:

type
  TStringListImpl = class(TInterfacedObject, IStringList)
  private
    FStringList: TStringList; // create in constructor, destroy in destructor
    // implementation etc.
  end;
Run Code Online (Sandbox Code Playgroud)

然后实现记录:

type
  TStringListRecord = record
  private
    FImpl: IStringList;
    function GetImpl: IStringList; // creates TStringListImpl if FImpl is nil
                                   // returns value of FImpl otherwise
  public
    procedure Add(const s: string); // forward to GetImpl.Add
    property StringList: TStringList read GetStringList; // forward to
                                                         // GetImpl.StringList
    // etc.
  end;
Run Code Online (Sandbox Code Playgroud)

记录中有接口的事实意味着编译器将自动处理引用计数,在创建和销毁副本时调用_AddRef和_Release,因此生命周期管理是自动的.这适用于永远不会包含对自身的引用的对象(创建一个循环) - 引用计数需要各种技巧来克服参考图中的循环.