4

我有一个数据树列表。我正在遍历树列表以匹配某些记录并将它们添加到通用 TList<>。除了所有记录值都成为为 TList 中的所有项目添加的最后一个之外,此方法有效。

这是一些代码:

type
  TCompInfo = record
  private
    class var
      FCompanyName    : string;
      FCompanyPath    : string;
      FCompanyDataPath: string;
      FCompanyVer     : string;
  public
    class procedure Clear; static;
    class property CompanyName : string read FCompanyName write FCompanyName;
    class property CompanyPath : string read FCompanyPath write FCompanyPath;
    class property CompanyDataPath : string read FCompanyDataPath write FCompanyDataPath;
    class property CompanyVer : string read FCompanyVer write FCompanyVer;
  end;
  TCompList = TList<TCompInfo>;

// variablies defined ...
var
  CompData : TCompData;
  AList : TCompList;

像这样添加记录:

  tlCompanyList.GotoBOF;
  for i := 0 to tlCompanyList.Count-1 do
  begin
    if colCompanyChecked.Value then
    begin
      inc(ItemsChecked);
      CompData.CompanyName := colCompanyName.Value;
      CompData.CompanyDataPath := colCompanyDataPath.Value;
      CompData.CompanyPath := colCompanyPath.Value;
      CompData.CompanyVer := colCompanyVersion.Value;
      AList.Add(CompData);
  end;
  tlCompanyList.GotoNext;

...或添加这样的记录:

  tlCompanyList.GotoBOF;
  for i := 0 to tlCompanyList.Count-1 do
  begin
    if colCompanyChecked.Value then
    begin
      inc(ItemsChecked);
      AList.Count := ItemsChecked;
      AList.Items[ItemsChecked-1].CompanyName := colCompanyName.Value;
      AList.Items[ItemsChecked-1].CompanyDataPath := colCompanyDataPath.Value;
      AList.Items[ItemsChecked-1].CompanyPath := colCompanyPath.Value;
      AList.Items[ItemsChecked-1].CompanyVer := colCompanyVersion.Value;
  end;
  tlCompanyList.GotoNext;

结果完全相同。AList.Items[0...Count-1] 都具有相同的值。单步执行代码,我可以看到正在捕获正确的数据,但是一旦我将新记录保存到 AList,所有以前的记录都会采用相同的值。这表明 TList 中的每个项目都是指向内存中同一记录的指针。如果记录所占用的内存发生变化,所有项目都会发生变化。这使自那以后,但不是我想要的。如何分配 TList 中的新记录以保存不同的数据?

我知道我可以通过其他方式完成最终结果,而且我确实做到了。现在使用泛型和记录,这对我来说更具教育意义。我正在使用德尔福 XE。

谢谢

4

1 回答 1

13

您已将记录的所有字段声明为“class var”。在一个类中,“class var”的值对于该类的所有实例都是相同的。实际上我从来没有对记录使用过“class var”,但我想记录类型的语义也是一样的。这意味着每当您更改一条记录中的字段值时,它都会在所有现有记录中更改。

尝试不使用“class var”和简单的“property”而不是“class property”。

于 2011-07-07T07:01:30.493 回答