无法在Delphi中设置TStringLists数组

时间:2011-10-13 14:04:05

标签: 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;

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

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

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

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

2 个答案:

答案 0 :(得分: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;

以下是包含评论的旧代码:

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; } 

答案 1 :(得分:4)

没有开始/结束对是问题。没有评论,

for i := 0 to emailPassword.Lines.Count - 1 do

循环只迭代行

oSLArray[i] := TStringList.Create;

oSLArray[i].Delimiter := ' '; 
循环后执行