-1

我在这里将 Tlist 放入字符串数组并不是什么大问题,但是我正在抛出 Array 我想列出所有要持续的值。

每次都列出最后一个值。我想要这样

价值1q

价值2q

价值3q

布拉布拉。所以数组中的 TList 我想列出所有元素。

对不起我的英语不好

public  var
  { Public declarations }
  Address : Array Of String;
  AddressList: Tlist;


//Form Create
 AddressList := Tlist.Create;
 SetLength(Address, 3);



//Copy Listview Button
var
  i : integer;
  AItem: TlistItem;
begin
  AddressList.Clear;

  for i := 0 to SelectedListView.Items.Count - 1 do
  begin
    AItem := SelectedListView.Items.Item[i];
    Address[0] := AItem.SubItems[0];
    Address[1] := AItem.Caption;
    Address[2] := AItem.SubItems[1];
    AddressList.Add(Address);
  end;

//Always being counted towards the last value
for i := 0 to AddressList.Count -1 do
    MultiUser.Text := TArrayStr(AddressList[i])[1]);
4

1 回答 1

7

我在这里看到的问题是动态数组是托管类型,并且依赖于引用计数。引用计数仅在数组被正确类型的变量引用时才有效。当您存储到 untypedPointer时,TList编译器无法正确计算引用。

除了这个基本的设计缺陷之外,您的程序中实际上只有一个数组。TList每次调用时,您只需向对象添加相同的指针Add。请记住,动态数组是引用类型,没有任何写时复制。所以他们表现得像真正的参考。

如果你有一个现代的 Delphi,那么你可以用一个类型安全的通用容器来解决这个问题。例如TList<TArray<string>>从哪里来。TList<T>_Generics.Collections

对于旧版本的 Delphi,您不能期望将动态数组存储在TList. 那根本不会飞。您可以自己破解引用计数,但您需要清晰的手和良好的理解。遇到你的代码的下一个程序员会鄙视你。

因此,对于旧版本的 Delphi,我建议您替换TListTObjectList. 设置OwnsObjectsTrue。并将动态数组替换stringTStringList.

旧版 Delphi 的另一种解决方案是使用多维数组:array of array of string.

于 2014-03-22T12:09:18.107 回答