英文:
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<TGItem>;
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>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论