【问题标题】:How to identify Delphi StringList object is created or not如何识别Delphi StringList对象是否创建
【发布时间】:2011-11-29 23:21:25
【问题描述】:

我已经在私有部分声明了 TStringList 的变量。在按钮单击事件中,我想访问该 TStringList 对象。

sVariable:= TStringList.Create;
sVariable.add('Test1');

现在,每当我每次单击该按钮时,都会将其新创建的内存分配给该变量。是否有任何属性/函数可以用来确定是否为该变量创建了对象,并且它也不会给出访问冲突错误?

【问题讨论】:

  • 小心,所有的答案都忘记初始化变量/字段,而是依赖于隐式初始化。
  • +1 用于访问确实:-)
  • @Downvoter Delphi 类实例确实是零初始化的。这确实是可以依靠的东西。每当您在析构函数中编写代码时,您都必须依赖它。

标签: delphi tstringlist


【解决方案1】:
if not Assigned(sVariable) then
  sVariable:= TStringList.Create;
sVariable.add('Test1');

【讨论】:

    【解决方案2】:

    另一种解决方法,扩展大卫的答案,是通过具有读取方法的属性。

    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;
    

    编辑:在重写的析构函数中添加了 Free 调用。

    【讨论】:

    • 如果列表可以在多个代码部分中使用,这是更好的方法,但如果只在一个地方访问它可能会过大。
    猜你喜欢
    • 2023-03-30
    • 2017-08-08
    • 1970-01-01
    • 2014-12-24
    • 1970-01-01
    • 1970-01-01
    • 2013-02-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多