我听过很多程序员,特别是Delphi程序员嘲笑使用'with'.
我认为它使程序运行得更快(只有一个对父对象的引用),并且如果使用得当,它更容易阅读代码(少于十几行代码并且没有嵌套).
这是一个例子:
procedure TBitmap32.FillRectS(const ARect: TRect; Value: TColor32);
begin
with ARect do FillRectS(Left, Top, Right, Bottom, Value);
end;
Run Code Online (Sandbox Code Playgroud)
我喜欢用with.我怎么了?
我很想知道为什么Delphi将记录类型属性视为只读:
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;
Run Code Online (Sandbox Code Playgroud)
如果我尝试为Rec属性的任何成员赋值,我将得到"左侧无法分配"错误:
procedure TForm1.DoSomething(ARec: TRec);
begin
Rec.A := ARec.A;
end;
Run Code Online (Sandbox Code Playgroud)
允许对底层字段执行相同操作:
procedure TForm1.DoSomething(ARec: TRec);
begin
FRec.A := ARec.A;
end;
Run Code Online (Sandbox Code Playgroud)
这种行为有什么解释吗?