Possible Duplicate:
Reference object instance created using “with” in Delphi
One method that I use to create query objects in Delphi follows the first code sample. It gives me a reference to the object and I can then pass the object to a function.
procedure SomeProcedure;
var
qry: TQuery;
begin
qry := TQuery.Create(nil);
with qry do
begin
Connection := MyConn;
SQL.Text := 'SELECT * FROM PEOPLE';
Open;
funcDisplayDataSet(qry);
Free;
end;
end;
Is it also possible to do this in a WITH statement where your Create object in contained in the WITH statement?
procedure SomeProcedure;
begin
with TQuery.Create(nil) do
begin
Connection := MyConn;
SQL.Text := 'SELECT * FROM PEOPLE';
Open;
funcDisplayDataSet( ??? ); // Here I'm unsure how to pass the object created...
Free;
end;
end;
Can I pass this dynamic object to a function like `funcDisplayDataSet(TQuery)?
I just would like to know if this is possible. I'm not looking for a summary on why the WITH statement is bad or good. There are other posts on StackOver flow with that discussion.*
That's not possible, in general, in a clean manner. Your options:
Self
.with
and create a local variable for the instance.Option 1 is viable if you have control over the class. But it leaves the class looking rather odd. Why would a class need an instance method that returned the instance? If you don't have control over the class then you could use a class helper as RRUZ suggests but I regard the use of class helpers as a last resort. I've never solved a problem with a class helper.
That leaves option 2. This would be how I would solve the problem.
What about using a class helper ?
type
TQueryHelper = class helper for TQuery
public
function Instance: TQuery;
end;
function TQueryHelper.Instance: TQuery;
begin
Result := Self;
end;
And use like this
With TQuery.Create(nil) do
begin
SQL.Text:='Select * from OTGH';
ShowMessage(Instance.SQL.Text);
end;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With