delphi - 将 TStringList 包装在记录中

标签 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;

如果能够取消这样一个通用实用程序类的创建和释放,那就太好了。

既然我们现在有了带有方法的记录,是否可以将像 TStringList 这样的类包装在 记录一下,这样我就可以:

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


end;

最佳答案

这是可能的。创建一个公开您想要的方法/对象的接口(interface):

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

实现接口(interface),并让它包装一个真正的TStringList:

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

然后实现记录:

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;

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

关于delphi - 将 TStringList 包装在记录中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1216819/

相关文章:

Delphi TreeView : Can I have different styles in one node's text?

delphi - 从 Delphi 打开和关闭外部程序

delphi - 如何在delphi中正确使用SQL where语句?

MySQL - 组合两条记录,每条记录的不同字段

syntax - 复制 OCaml 中的字段

delphi - 如何防止 TStrings.SaveToFile 创建最终的空行?

Delphi - 打开文本文件共享冲突

ruby-on-rails - rails 4 x paper_trail : track which attributes are updated and display their new value

c++ - 在 TStringList 中添加对象

delphi - Delphi Prism 中 TStringList 的替代品。