在不使用变量的情况下在“with”语句中创建对象

Emr*_*men 1 delphi variables with-statement declare

var 
  UserName, NickName, UserID: string;
begin
  with TStringList.Create do
  begin
    CommaText := 'ali,veli,4950';
    UserName := x[0];  //what is x ? (x is Tstringlist.create)
    NickName := x[1];
    UserID := x[2];
  end;   
end;
Run Code Online (Sandbox Code Playgroud)

如果我使用下面的代码,它就可以工作。但我不想声明一个变量。我可以将它与任何变量一起使用吗?

with声明中,我如何使用它?

var 
  tsl: TStringList;
begin
  tsl := TStringlist.Create;
  with tsl do
  begin
    CommaText := 'ali,veli,4950';
    UserName := tsl[0]; 
    NickName := tsl[1];
    UserID := tsl[2];
  end;
end;
Run Code Online (Sandbox Code Playgroud)

Rem*_*eau 6

当在with语句中直接创建对象时,没有引用该对象的语法(除非它提供了一个引用自身的成员,这种情况非常罕见),因此您通常必须使用变量,就像您的底层代码所做的那样。

此外,这两个代码都在泄漏该TStringList对象,因为您在使用完Free()它后并没有调用它。

话虽如此,在这个特定的例子中,[]操作符只是访问TStrings.Strings[]默认属性的简写,你可以在不需要创建TStringList对象的变量的情况下访问它,就像你对TStrings.CommaText属性所做的一样,例如:

var 
  UserName, NickName, UserID: string;
Begin
  with TStringList.Create do
  try
    CommaText := 'ali,veli,4950';
    UserName := Strings[0];
    NickName := Strings[1];
    UserID := Strings[2];
  finally
    Free;
  end;
end;
Run Code Online (Sandbox Code Playgroud)