delphi – 在记录中包装TStringList
发布时间:2020-12-15 09:44:09 所属栏目:大数据 来源:网络整理
导读:我倾向于使用Delphi的TStringList进行文本操作,所以我写了很多程序/函数,如: var TempList: TStringList;begin TempList:= TStringList.Create; try // blah blah blah do stuff with TempList finally TempList.Free; end;end; 切断创建和释放这样一个常见
我倾向于使用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; 解决方法
这是可能的.创建一个公开所需方法/对象的接口:
type IStringList = interface procedure Add(const s: string); // etc. property StringList: TStringList read GetStringList; // etc. end; 实现接口,并让它包装一个真正的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; 记录中有接口的事实意味着编译器将自动处理引用计数,在创建和销毁副本时调用_AddRef和_Release,因此生命周期管理是自动的.这适用于永远不会包含对自身的引用的对象(创建一个循环) – 引用计数需要各种技巧来克服参考图中的循环. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |