Reference object instance created using “with” in Delphi

后端 未结 9 1337
生来不讨喜
生来不讨喜 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:21

    You should never use with either because future changes might introduce more into that scope than you intended.

    Take this for instance:

    procedure Test;
    var
        x: Integer;
    begin
        with TSomeObject.Create do
        begin
            DoSomethingWithX(x);
            Free;
        end;
    end;
    

    and then later on you tuck on a X property on the TSomeObject class. Now, which X do you think it's going to use? The local variable or the X property of the object?

    The best solution is always to just create a local variable with a short name, and alias the object to that variable.

    procedure Test;
    var
        x: Integer;
        o: TSomeObject;
    begin
        o := TSomeObject.Create;
        o.DoSomethingWithX(x);
        o.Free;
    end;
    
    0 讨论(0)
  • 2020-12-03 19:23

    An addition to Brian's example on a Notify handler is to use an absolute variable (win32 only):

    procedure Notify( Sender : TObject ); 
    var 
      Something : TSomeThing absolute Sender;
    begin 
      if Sender is TSomething then 
      begin
        VerySimpleProperty := Something.Something;
        OtherProperty := Something.SomethingElse;
      end;
    end;
    

    It basically avoids having to assign a local variable or have a lot of type casts.

    0 讨论(0)
  • 2020-12-03 19:24

    for FMX, you should use GetObject example:

    with TLabel.Create(box1) do
    begin
        Font.Size := 34;
        Font.Style := [TFontStyle.fsBold];
        TextAlign := TTextAlign.taCenter;
        box1.AddObject(GetObject);
    end;;
    
    0 讨论(0)
提交回复
热议问题