Nal*_*alu 3 delphi tstringlist
我在私有部分声明了TStringList的变量.在按钮单击事件中,我想访问该TStringList对象.
sVariable:= TStringList.Create;
sVariable.add('Test1');
Run Code Online (Sandbox Code Playgroud)
现在每当我点击该按钮时,每次将其新创建的内存分配给该变量.是否有任何属性/函数可用于确定是否为该变量创建了对象,并且它也不会给出访问冲突错误?
if not Assigned(sVariable) then
sVariable:= TStringList.Create;
sVariable.add('Test1');
Run Code Online (Sandbox Code Playgroud)
另一种接近它的方法,扩展David的答案,是通过一个带有read方法的属性.
TMyForm = class (TForm)
private
FStrList : TStringList;
public
property StrList : TStringList read GetStrList;
destructor Destroy; override;
end;
implementation
function TMyForm.GetStrList : TStringList;
begin
if not Assigned(FStrList) then
FStrList := TStringList.Create;
Result := FStrList;
end;
destructor TMyForm.Destroy;
begin
FStrList.Free;
inherited;
end;
Run Code Online (Sandbox Code Playgroud)
编辑:在重写的析构函数中添加了免费调用.