有没有一种方法可以引用使用“with”语句创建的对象实例?
例如:
with TAnObject.Create do
begin
DoSomething(instance);
end;
在DoSomething函数中,您需要使用实例引用,就好像您从一个变量声明的引用传递实例一样。
例如:
AnObject := TAnObject.Create;
感谢您的选择。
有没有一种方法可以引用使用“with”语句创建的对象实例?
例如:
with TAnObject.Create do
begin
DoSomething(instance);
end;
在DoSomething函数中,您需要使用实例引用,就好像您从一个变量声明的引用传递实例一样。
例如:
AnObject := TAnObject.Create;
你可以采用以下方法:
// implement:
type
TSimpleMethod = procedure of object;
function GetThis(const pr: TSimpleMethod): TObject;
begin
Result := TMethod(pr).Data;
end;
// usage:
with TStringList.Create do
try
CommaText := '1,2,3,4,5,6,7,8,9,0';
ShowText(TStringList(GetThis(Free)));
finally
Free;
end;
或者类助手:type
TObjectHelper = class helper For TObject
private
function GetThis: TObject; Inline;
public
property This: TObject read GetThis;
end;
...
function TObjectHelper.GetThis: TObject;
begin
Result := Self;
end;
但是实际上,之前的回答是正确的:你最好忘记使用 "with" 语句。
你不应该使用with
,因为未来的更改可能会将比预期更多的内容引入该作用域。
以这个为例:
procedure Test;
var
x: Integer;
begin
with TSomeObject.Create do
begin
DoSomethingWithX(x);
Free;
end;
end;
之后你在TSomeObject类上添加了一个X属性,那么你认为它会使用哪个X呢?本地变量还是对象的X属性?
最好的解决方案总是创建一个带有短名称的本地变量,并将对象别名为该变量。
procedure Test;
var
x: Integer;
o: TSomeObject;
begin
o := TSomeObject.Create;
o.DoSomethingWithX(x);
o.Free;
end;
var
MyInstance: TMyObject;
begin
MyInstance := TMyObject.Create;
with MyInstance do
try
Foo;
Bar;
DoSomething(MyInstance);
finally
Free;
end;
end;
procedure Notify( Sender : TObject );
var
Something : TSomeThing absolute Sender;
begin
if Sender is TSomething then
begin
VerySimpleProperty := Something.Something;
OtherProperty := Something.SomethingElse;
end;
end;
这基本上避免了分配本地变量或进行大量类型转换的需求。
With TMyForm.Create( Owner ) do
try
ShowModal
finally
Free;
end;
procedure Notify( Sender : TObject );
begin
With Sender as TSomething do
VerySimpleProperty := Something
end;
有一个可行的好方法来实现这个。 在项目单元中定义这个解决方法函数。
// 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;
使用示例。
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;
在Delphi中最好的方法是使用一个变量来处理该实例。
对于 FMX,你应该使用 GetObject 函数 例如:
with TLabel.Create(box1) do
begin
Font.Size := 34;
Font.Style := [TFontStyle.fsBold];
TextAlign := TTextAlign.taCenter;
box1.AddObject(GetObject);
end;;
现在还不可能,但我们可以通过说服编译器的创建者来实现它:
With TForm1.Create (Nil) Do // New TForm1 instance
Try
LogForm ("); // That same instance as parameter to an outer method (solution)
"ShowModal; // Instance.ShowModal
Finally
"Free; // Instance.Free
End;
我的建议是: