Reference object instance created using “with” in

2019-01-12 03:57发布

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

Example:

with TAnObject.Create do
begin
  DoSomething(instance);
end;

Where DoSomething would use the instance reference as if you were passing an instance from a variable declared reference to the object created.

Example:

AnObject := TAnObject.Create;

Thanks.

8条回答
Bombasti
2楼-- · 2019-01-12 04:21

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.

查看更多
Animai°情兽
3楼-- · 2019-01-12 04:33

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 <TObjectN>
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;
查看更多
登录 后发表回答