Reputation: 368
I want to create independent copies of DynamicArrays involving class (not Records). I am using Delphi XE5. In the example code below, after all the assignments are done, all copies of the dynamic array contain the same values. It has been explained in "Copy" does not create independent copy of Dynamic Array that it is an expected behviour since classes are involved. The problem I run into is that I can't avoid using classes. The type definitions are generated by Delphi by reading in a WSDL. It is a monsterous file with close to 5000 lines in it. Trying to modifying type definitions at length woud not be advisable and will open another can of worms.
TYPE
TX = class(TRemotable)
private
<..vars and functions..>
published
<..properties..>
end;
TArray_Of_TX = array of TX;
TDATA_RECORD = class(TRemotable)
private
<..vars and functions..>
public
destructor Destroy; override;
published
<..other properties..>
property Y: TArray_Of_TX Index (IS_OPTN or IS_UNBD) read FY write SetY stored ABooleanVariable;
end;
VAR
X: TArray_Of_TX;
DataRecord_1, DataRecord_2, DataRecord_3: TData_Record;
BEGIN
SetLength(X, 1);
X[0] := T_X_Type.Create();
X[0].var := 'some value 1';
DataRecord_1 := TData_Record.create();
DataRecord_1.Y := copy(X);
X[0].var := 'some value 2';
DataRecord_2 := TData_Record.create();
DataRecord_2.Y := copy(X);
X[0].var := 'some value 3';
DataRecord_3 := TData_Record.create();
DataRecord_3.Y := copy(X);
X[0].var := 'some value 4';
//At this time, I would like to have all copies of TArray_of_TX have different
//values for various member fields but they all have the same value--the last
//value assigned to X[0].var!
Thinking that the Copy()
is not going to work for class objects, I tried setLength(DataRecord_1.Y, 1)
but it raised a compiler error "Constant object cannot be passed as var parameter".
An easy solution may seem to be to create as many instances of "X" variable as needed but the problem is it could be quite a large number (not known at design time). Besided, that would be very inefficient and inelagent. It would also introduce its own challenges of keeping track of using which variable when, etc etc.
Upvotes: 1
Views: 419
Reputation: 76547
You can copy the array like so:
function CloneArray(original: TArray_Of_TX): TArray_Of_TX;
var
i: integer;
copy: TX;
begin
Result.SetLength(SizeOf(original));
for i:= 0 to SizeOf(original) -1 do begin
copy:= TX.Create;
copy.assign(original[i]);
Result[i]:= copy;
end; {for i}
end;
This version does not use generics, because I'm not sure how to create a generic version using a dynamic array.
Upvotes: 1