【问题标题】:list index out of bounds (0)列表索引越界 (0)
【发布时间】:2012-01-08 15:45:38
【问题描述】:

我发布了一个关于在 Delphi 的表单中修复方法声明中的错误的问题,但是在修复它之后,在编译时弹出另一个错误,并且它说项目 project1.exe 引发异常类 EStringListError 并带有消息“列表索引超出范围” (0)'.当我按下 continue 时它不起作用但是当我按下 break 时它在代码上闪烁 neraz:=true; 这是我下面的代码

Procedure Reload;
var
    i:integer;
begin
form1.ListBox1.Clear;
form1.ListBox2.Clear;
if neraz then
HD;
neraz:=true;//..................here
form1.Label3.Caption:='free: '+inttostr(vs*32)+' byte'+#10#13+'cluster size = 32 bytes';
  i:=TABLE[nk1].nach;
   KolP1:=0; KolP2:=0;
   while (FAT[i]<>1024)  do begin
      if TABLE[fat[i]].tip then begin
          form1.ListBox1.Items.Add('dir>'+TABLE[fat[i]].name);
          inc(kolP1);
      end
      else
          if TABLE[fat[i]].format='txt' then
                form1.ListBox1.Items.Add('f_text> '+TABLE[fat[i]].name+'.'+TABLE[fat[i]].format)
          else
                form1.ListBox1.Items.Add('f_bin> '+TABLE[fat[i]].name+'.'+TABLE[fat[i]].format);
      if (fat[i]<>0) then
      i:=fat[i];
   end;
   i:=TABLE[nk2].nach;
   while (FAT[i]<>1024)  do begin
      if TABLE[FAT[i]].tip then begin
          form1.ListBox2.Items.Add('dir>'+TABLE[fat[i]].name);
          inc(kolP2)
      end
      else
          if TABLE[fat[i]].format='txt' then
                form1.ListBox2.Items.Add('f_text> '+TABLE[fat[i]].name+'.'+TABLE[fat[i]].format)
          else
                form1.ListBox2.Items.Add('f_bin> '+TABLE[fat[i]].name+'.'+TABLE[fat[i]].format);
      if (fat[i]<>0) then
      i:=fat[i];
   end;
   vfail;
end;


procedure HD;
var
  i: integer;
begin
  for i := 0 to 49 do begin
    with form2.ListView1.Items[i] do begin
      SubItems[0] := TABLE[i].name;
      SubItems[1] := TABLE[i].format;
      if TABLE[i].tip then
        SubItems[2] := 'folder'
      else
        SubItems[2] := 'file';
      SubItems[3] := IntToStr(TABLE[i].nach);
      SubItems[4] := IntToStr(TABLE[i].razmer);
    end;
    form2.ListView2.Items[i].SubItems[0] := IntToStr(fat[i]);
  end;
end;

【问题讨论】:

  • 你的代码真的是这样格式化的吗?如果是这样,那么您迫切需要学习如何正确缩进代码。特别是因为您正在混合单个语句和复合语句块。在最好的情况下,这会让生活变得艰难,但如果没有缩进纪律,您的代码就无法维护。
  • 如果你的代码不是这样格式化的,但碰巧你只是把它粘贴得这么丑,但你根本不在乎,那么你就会怀疑你对 SO 社区帮助你的真正兴趣。
  • HD 中的 for 循环假定两个列表视图中都有 50 个项目。你确定是这样吗?任一列表视图为空都可能触发异常,以及任一列表视图没有/不再有任何子项。
  • 越界通常意味着您正在尝试访问 for 循环之外的索引,或者您尝试访问的索引不存在。

标签: delphi


【解决方案1】:

当您尝试访问空的 TStrings 实例的成员时,异常类 EStringListError 引发错误列表索引超出范围 (0)。最有可能的候选者是列表项的SubItems 属性。

你似乎掉进了一个很常见的陷阱。尽管您已经为列表视图创建了列,但您还需要为每个列表项填写SubItems 列表。一个简单的解决方案是像这样修改HD

with form2.ListView1.Items[i] do begin
  while SubItems.Count<5 do
    SubItems.Add('');
  SubItems[0] := ...

虽然实际上在创建列表项的同时添加子项可能会更好。但是我没有显示代码,因为您没有包含填充列表的程序部分。

【讨论】:

    猜你喜欢
    • 2021-07-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多