Reference object instance created using “with” in Delphi

后端 未结 9 1400
生来不讨喜
生来不讨喜 2020-12-03 18:17

is there a way to reference an object instance that is created using the \"with\" statement?

Example:

with TAnObject.Create do
begin
  DoSomething(in         


        
9条回答
  •  鱼传尺愫
    2020-12-03 19:10

    There is a working fine hack to do so. Define this workaround function somwhere in project unit.

    // use variable inside 'with ... do'
    // WSelf function returns TObject associated with its method.
    //   I would recommend to use the method 'Free'
    // WSelf(Free) as 
    type TObjectMethod = procedure of object;
    function WSelf(const MethodPointer: TObjectMethod): TObject;
    begin
      Result := TMethod(MethodPointer).Data;
    end;
    

    Usage example.

    var
        SL: TStringList;
    begin
        SL := TStringList.Create;
        try
            with TStringList.Create do
            try
                Add('1');
                Add('2');
                Add('3');
                // (WSelf(Free) as TStringList) references to the object
                //   created by TStringList.Create
                SL.Assign(WSelf(Free) as TStringList);
            finally
                Free;
            end;
        finally
            ShowMessage(SL.Text);
            SL.Free;
        end;
    end;
    

提交回复
热议问题