无法在Delphi中设置TStringLists数组

use*_*626 5 delphi

Var
  i : Integer;
  j : Integer;
  oSLArray : array of TStringList;
  oSL : TStringList;
begin
  SetLength(oSLArray, emailPassword.Lines.Count);
  for i := 0 to emailPassword.Lines.Count - 1 do
    {oSLArray[i] := TStringList.Create;
    oSLArray[i].Delimiter := ' ';
    oSLArray[i].DelimitedText := emailPassword.Lines[i];
    for j := 0 to oSLArray[i].Count-1 do begin
      Showmessage( oSLArray[i].Strings[j] );
    end; }
    oSL := TStringList.Create;
    oSL.Delimiter := ' ';
    oSL.DelimitedText := emailPassword.Lines[i];
    for j := 0 to oSL.Count-1 do begin
      Showmessage( oSL[j] );
    end;
  end;
Run Code Online (Sandbox Code Playgroud)

我正在尝试创建一个TStringLists数组,读取来自RichEdit'EmailPassword'的内容,然后打印它(当我到达目的地时,我会把它放在一个数组中).

当我取消注释oSLarray时,我收到了访问冲突.当我用oSL尝试它时,没有任何打印.

现在,我理解访问冲突意味着指针可能没有正确设置,因为我认为访问冲突发生在oSLArray [i]:= TStringList.Create.

我只是错过了一些小事吗?

Joh*_*ica 7

我已经纠正了代码,我相信这段代码会起作用,但我只是在脑海中测试过.

var 
  i : Integer; 
  j : Integer; 
  oSLArray : array of TStringList; 
  oSL : TStringList; 
begin
  if not(Assigned(emailpassword)) then exit;
  SetLength(oSLArray, emailPassword.Lines.Count); 
  for i := 0 to emailPassword.Lines.Count - 1 do begin
    oSLArray[i] := TStringList.Create; 
    oSLArray[i].Delimiter := ' '; 
    oSLArray[i].DelimitedText := emailPassword.Lines[i]; 
    for j := 0 to oSLArray[i].Count-1 do begin 
      Showmessage( oSLArray[i].Strings[j] );   <<--- The error has here
    end; {for j} 
  end; {for i}

    //oSL := TStringList.Create; 
    //try
    //  oSL.Delimiter := ' '; 
    //  oSL.DelimitedText := emailPassword.Lines[i]; 
    //  for j := 0 to oSL.Count-1 do begin 
    //    Showmessage( oSL[j] ); 
    //  end; {for j}
    //finally
    //  oSL.Free;
    //end; {try}
    //end; {for i} 
end;
Run Code Online (Sandbox Code Playgroud)

这是你的旧代码和评论:

for i := 0 to emailPassword.Lines.Count - 1 do //don't forget begin
  oSLArray[i] := TStringList.Create; 
  oSLArray[i].Delimiter := ' '; 
  oSLArray[i].DelimitedText := emailPassword.Lines[i]; 
//<<<--  Here for i loop should end, but it does not.
    for j := 0 to oSLArray[i].Count-1 do begin 
 //You loop though all members of OSLArtray, even though only the first item is set, 
 //the rest is unassigned.
      Showmessage( oSLArray[i].Strings[j] );  <<-- Access Violation 
    end; } 
Run Code Online (Sandbox Code Playgroud)

  • 啊! 失踪的`开始'!因为我从不编写没有`begin`的代码,所以我失去了发现它可能会丢失的能力. (2认同)

Tot*_*oto 5

缺少开始/结束对就是问题所在。如果没有评论,

for i := 0 to emailPassword.Lines.Count - 1 do
Run Code Online (Sandbox Code Playgroud)

循环仅迭代该行

oSLArray[i] := TStringList.Create;
Run Code Online (Sandbox Code Playgroud)

线

oSLArray[i].Delimiter := ' '; 
Run Code Online (Sandbox Code Playgroud)

在循环之后执行。

  • +1提供关于为什么OP的代码不起作用的解释。 (2认同)