Effectively change recording elements in Generics in Delphi XE

AFAIK, we cannot assign direct values ​​to record elements if the specified record is in the general structure.

For example, having:

type TMyRec = record Width: integer; Height: integer; end; var myList: TList<TMyRec>; ... myList[888].Width:=1000; //ERROR here: Left side cannot be assigned. ... 

So far, I have used a temporary variable to overcome this:

 var ... temp: TMyRec; ... begin ... temp:=myList[999]; temp.Width:=1000; myList[999]:=temp; ... end; 

Ugly, slow but working. But now I want to add a dynamic array to TMyRec :

 type TMyRec = record Width: integer; Height: integer; Points: array or TPoint; end; 

... or any other data structure that can become large, so copying back and forth into a temporary variable is not an option.

The question arises: how to change a member of a record when this record is in the general structure without the need to copy it in a temporary var?

TIA for your feedback

+4
source share
1 answer

A dynamic array variable is just a reference to an array. It is stored in the record as a single pointer. This way you can continue your current approach without over copying. Copying an element to a temporary variable copies only the reference to the array and does not copy the contents of the array. And even better, if you assign elements to an array, you don't need a copy at all. You can write:

 myList[666].Points[0] := ... 

If you really have a record that is really big, you better use a class rather than a record. Since the class instance is a reference, the same argument applies as above. For this approach, you may prefer TObjectList <> to TList <>. The advantage of TObjectList <> is that you can set the OwnsObjects property to True and let the list be responsible for destroying its members.

Then you can write

 var myList: TObjectList<TMyClass> .... myList[666].SomeProp := NewValue; 
+6
source

Source: https://habr.com/ru/post/1401533/


All Articles