为什么编译器不允许for ... in循环中的赋值?
procedure TForm1.Button1Click(Sender: TObject);
Var
ars : Array [0..10] of Integer;
s : Integer;
ct : Integer;
begin
ct := 0;
for s in ars do
Begin
s := ct; // Does not compile!
Inc(ct);
End;
End;
Run Code Online (Sandbox Code Playgroud)
这是不受支持的,因为即使是简单的循环迭代器变量也无法在"正常"for循环中进行修改.即使这在for-in中得到支持,在这种情况下也没有多大意义.
整数是值类型,所以在循环的每次迭代,将实现所有的是,小号将被初始化为从一个元素阵列的值,然后š通过覆盖的Ct.
但是,数组的内容将不会被修改,并且该代码的净效应将是"没有变化".
要获得您对for-in的期望,您必须能够使用合适的引用类型(在本例中为PInteger - 指向整数的指针)进行迭代,从而产生对数组元素的引用,而不是这些元素的值的副本.然后可以使用解除引用的指针分配每个元素的新值:
var
ars : array [0..10] of Integer;
s : PInteger;
ct : Integer;
begin
ct := 0;
for s in ars do // << this WON'T yield pointers to the array elements ..
begin
s^ := Ct; // .. but if it did you could then write this
Inc(ct);
end;
end;
Run Code Online (Sandbox Code Playgroud)
但是不要兴奋 - 这也不会起作用,它只是表明问题的本质源于参考与价值的差异.
| 归档时间: |
|
| 查看次数: |
958 次 |
| 最近记录: |