“左侧不能分配给"用于 Delphi 中的记录类型属性 [英] "Left side cannot be assigned to" for record type properties in Delphi
问题描述
我很想知道为什么 Delphi 将记录类型属性视为只读:
I'm curious to know why Delphi treats record type properties as read only:
TRec = record
A : integer;
B : string;
end;
TForm1 = class(TForm)
private
FRec : TRec;
public
procedure DoSomething(ARec: TRec);
property Rec : TRec read FRec write FRec;
end;
如果我尝试为 Rec 属性的任何成员分配一个值,我将收到左侧无法分配给"错误:
If I try to assign a value to any of the members of Rec property, I'll get "Left side cannot be assigned to" error:
procedure TForm1.DoSomething(ARec: TRec);
begin
Rec.A := ARec.A;
end;
同时对底层字段做同样的事情是允许的:
while doing the same with the underlying field is allowed:
procedure TForm1.DoSomething(ARec: TRec);
begin
FRec.A := ARec.A;
end;
对这种行为有什么解释吗?
Is there any explanation for that behavior?
推荐答案
由于Rec"是一个属性,编译器对它的处理有点不同,因为它必须首先评估属性 decl 的读取".考虑一下,这在语义上等同于您的示例:
Since "Rec" is a property, the compiler treats it a little differently because it has to first evaluate the "read" of the property decl. Consider this, which is semantically equivalent to your example:
...
property Rec: TRec read GetRec write FRec;
...
如果你这样看,你可以看到对Rec"的第一次引用(在点'.'之前),必须调用GetRec,它会创建一个临时的Rec本地副本.这些临时文件设计为只读".这就是您遇到的问题.
If you look at it like this, you can see that the first reference to "Rec" (before the dot '.'), has to call GetRec, which will create a temporary local copy of Rec. These temporaries are by design "read-only." This is what you're running into.
您可以在此处做的另一件事是将记录的各个字段分解为包含类的属性:
Another thing you can do here is to break out the individual fields of the record as properties on the containing class:
...
property RecField: Integer read FRec.A write FRec.A;
...
这将允许您通过属性直接分配给类实例中该嵌入记录的字段.
This will allow you to directly assign through the property to the field of that embedded record in the class instance.
这篇关于“左侧不能分配给"用于 Delphi 中的记录类型属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!