“左侧不能分配给”用于Delphi中的记录类型属性 [英] "Left side cannot be assigned to" for record type properties in Delphi

查看:104
本文介绍了“左侧不能分配给”用于Delphi中的记录类型属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很好奇知道为什么Delphi将记录类型属性视为只读:

  TRec = record 
A:整数
B:string;
结束

TForm1 = class(TForm)
private
FRec:TRec;
public
procedure DoSomething(ARec:TRec);
属性Rec:TRec读FRec写FRec;
结束

如果我尝试为Rec属性的任何成员分配一个值,我会得到左侧无法分配给错误:

  procedure TForm1.DoSomething(ARec:TRec); 
begin
Rec.A:= ARec.A;
结束

同时对底层字段进行相同:

  procedure TForm1.DoSomething(ARec:TRec); 
begin
FRec.A:= ARec.A;
结束

有没有解释这个行为?



Regards

解决方案

由于Rec是一个属性,因此编译器会稍微不同,因为它必须首先评估读属性声明。考虑这一点,这在语义上等同于你的例子:

  ... 
属性Rec:TRec读取GetRec写FRec ;
...

如果你这样看,你可以看到第一个引用Rec(在点之前),必须调用GetRec,这将创建Rec的临时本地副本。这些临时性设计是只读的。这就是你正在进行的事情。



另一件你可以在这里做的是将记录的各个字段作为包含类的属性:

  ... 
属性RecField:整数读FREC.A写FRec.A;
...

这将允许您通过属性直接分配到该类实例中的嵌入式记录。


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;

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?

Regards

解决方案

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;
...

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屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆