如何获取包含相同记录类型的 Delphi 记录,以将整个数组克隆到新实例中?

huangapple go评论64阅读模式
英文:

How do I get Delphi record with TArray in it, of same record type, to clone whole array to a new instance?

问题

使用以下方法可以创建未指定“深度”的深度分支结构:

TGItem = record
  NameShort: String;
  NameLong: String;
  Formula: String;
  Components: TArray<TGItem>;
  procedure Init;
end;

var 
 A, B: TGItem;

 B := A; 

在A和B的.Components都指向相同的数组,但我想复制数组。如何做到这一点?

Version 10.4

Edit/Current progress:

class operator Assign(var Dest: TGItem; const [ref] Src: TGItem);

以及

class operator TGItem.Assign(var Dest: TGItem; const [ref] Src: TGItem);
begin
  // 在这里放什么?
end;
英文:

With this it's possible to create deep branching structures of unspecified 'depth'

TGItem = record
  NameShort:            String;
  NameLong:             String;
  Formula:              String;
  Components:           TArray&lt;TGItem&gt;;
  procedure Init;
end;

var 
 A,B: TGItem;

 B := A;  

The .Components in both A and B point to same array, but I want to duplicate the array. How do I do that?

Version 10.4

Edit/Current progress:

class operator Assign(var Dest: TGItem; const [ref] Src: TGItem);

and

class operator TGItem.Assign(var Dest: TGItem; const [ref] Src:TGItem);
begin
  // What to put here?
end;

答案1

得分: 1

function TGItem.Clone: TGItem;
begin
  Result.Init;    
  Result.NameShort        := Self.NameShort;
  Result.NameLong         := Self.NameLong;
  Result.Formula          := Self.Formula;
  Setlength(Result.Components, Length(Self.Components));
    
  var I: Integer;
  for I := 0 to Length(Result.Components)-1 do
  begin
    Result.Components[I] := Self.Components[I].Clone;
  end;    
end;

似乎有效,而不是使用 B := A,我使用 B := A.Clone,它执行递归复制并创建一个新的克隆的分支结构(而不是指向旧结构)。


<details>
<summary>英文:</summary>

function TGItem.Clone: TGItem;
begin
Result.Init;
Result.NameShort := Self.NameShort;
Result.NameLong := Self.NameLong;
Result.Formula := Self.Formula;
Setlength(Result.Components, Length(Self.Components));

var I: Integer;
for I := 0 to Length(Result.Components)-1 do
begin
Result.Components[I] := Self.Components[I].Clone;
end;
end;


Seems to work, instead of `B := A` I use `B := A.Clone` and it does a recursive copy and creates a new cloned branching structure (instead of pointing to the old structure).

</details>



huangapple
  • 本文由 发表于 2023年3月3日 17:55:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/75625562.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定