在Delphi中使用"with"创建的引用对象实例

8 delphi with-statement

有没有办法引用使用"with"语句创建的对象实例?

例:

with TAnObject.Create do
begin
  DoSomething(instance);
end;
Run Code Online (Sandbox Code Playgroud)

DoSomething将使用实例引用,就像您将实例从变量声明引用传递给创建的对象一样.

例:

AnObject := TAnObject.Create;
Run Code Online (Sandbox Code Playgroud)

谢谢.

Ale*_*lex 15

那么,你可以使用这样的方法:

// 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;
Run Code Online (Sandbox Code Playgroud)

或班级助手:

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;
Run Code Online (Sandbox Code Playgroud)

但实际上,之前的回复是正确的:你最好忘记"with"语句.

  • +1 :) 当我最初做 Delphi 时,这些辅助工具都不存在。 (2认同)
  • 很有趣看到这一点,因为我上周写的这篇博客文章将于下周安排(当我真的忙着为Delphi Live!会议做好准备时):http://wiert.wordpress.com/2009/04/27/delphi-bizarre-use-of-class-helpers-circumvent-with/PS:pitty我无法阅读俄语和谷歌俄语 - >英语翻译忘记了翻译你非常有趣的博客! (2认同)

ang*_*son 12

您永远不应该使用它们with,因为未来的更改可能会在您的预期范围内引入更多内容.

以此为例:

procedure Test;
var
    x: Integer;
begin
    with TSomeObject.Create do
    begin
        DoSomethingWithX(x);
        Free;
    end;
end;
Run Code Online (Sandbox Code Playgroud)

然后你就可以在TSomeObject类上使用X属性了.现在,您认为它将使用哪个X?对象的局部变量或X属性?

最好的解决方案始终是创建一个具有短名称的局部变量,并将该对象别名为该变量.

procedure Test;
var
    x: Integer;
    o: TSomeObject;
begin
    o := TSomeObject.Create;
    o.DoSomethingWithX(x);
    o.Free;
end;
Run Code Online (Sandbox Code Playgroud)

  • 另见http://stackoverflow.com/questions/71419/whats-wrong-with-delphis-with (4认同)