gpt4 book ai didi

delphi - 如何将 record 类型的记录添加到 TList<> 中?

转载 作者:行者123 更新时间:2023-12-03 15:18:04 49 4
gpt4 key购买 nike

我有一个数据树列表。我循环遍历树列表以匹配某些记录并将它们添加到通用 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 中分配新记录来保存不同的数据?

我知道我可以通过其他方式实现最终结果,而且我确实做到了。对于现在使用泛型和记录的我来说,这已经变得更具教育意义。我正在使用 Delphi XE。

谢谢

最佳答案

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

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

关于delphi - 如何将 record 类型的记录添加到 TList<> 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6606826/

49 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com