Reference object instance created using “with” in Delphi

后端 未结 9 1406
生来不讨喜
生来不讨喜 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-03 19:10

    I've learnt the hard way - only use 'With' in the following scenarios:

    With TMyForm.Create( Owner ) do
      try
        ShowModal
      finally
        Free;
      end;
    
    
    procedure Notify( Sender : TObject );
    begin
      With Sender as TSomething do
        VerySimpleProperty := Something      
    end;
    

    i.e keep the visibility of With as simple as possible. When you take into account the fact that the debugger cant resolve 'With', it's actually better and clearer to use a simple local variable or to fully declare the target i.e MyRecord.Something

提交回复
热议问题