开发者

How to modify TList<record> value?

Delphi 20开发者_StackOverflow中文版10 How to modify TList < record > value ?

type TTest = record a,b,c:Integer end;
var List:TList<TTest>;
    A:TTest;
    P:Pointer;
....
....

List[10] := A;  <- OK
List[10].a:=1;  <- Here compiler error : Left side cannot be assined to
P:=@List[10];   <- Error: Variable requied


A := List[10];
A.a := 1;
list[10] := A;

You don't have to do this with objects because they're reference types, (accessed through a pointer which the compiler manages internally to keep it out of your hair,) but records are value types so it doesn't work that way.


You've hit upon a snag with using records.

Consider this code:

function Test: TTest;
begin
    ...
end;

Test.a := 1;

What your code looks like to the compiler is actually this:

TTest temp := Test;
temp.a := 1;

The compiler is telling you, with the error message, that the assignment is pointless, since it will only assign a new value to a temporary record value, which will be instantly forgotten.

Also, the @List[10] is invalid because List[10] again returns only a temporary record value, so taking the address of that record is rather pointless.

However, reading and writing the whole record is OK.

So to summarize:

List[10] := A;  <- writing a whole record is OK
List[10].a:=1;  <- List[10] returns a temporary record, pointless assignment
P:=@List[10];   <- List[10] returns a temporary record, its address is pointless


If you want to store records, dynamic arrays are more suited to handling them :

type TTest = record a,b,c : Integer end;
type TTestList = array of TTest;
var List:TTestList;
    A:TTest;
    P:Pointer;
....
....

SetLength( List, 20 );
List[10]   := A; //<- OK
List[10].a := 1; //<- Ok
P := @List[10];  //<- Not advised (the next SetLength(List,xx) will blow the address away),
                 //   but technically works

If you need to add methods to manipulate these data, you can store this array as the field of a class, and add your methods to this class.


If you need to manipulate objects in that form, it is better to use TObjectList instead of TList, and define the structure as a class rather than a record:

type TTest = class a,b,c:Integer end;
var List:TObjectList<TTest>;
    A:TTest; // A is an object so there's no need for a pointer
....
....
List.Add(TTest.Create);
List.Last.a := 1;
A:=List.Last;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜