Delphi:在“ for In”中使用的变量。无法分配! [英] Delphi : Variable used in the "for In" cannot be assigned!

查看:110
本文介绍了Delphi:在“ for In”中使用的变量。无法分配!的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么编译器不允许for ... in循环中的赋值?

Why is the assignment in the for...in loop disallowed by the compiler?

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;


推荐答案

不支持此功能,就像简单的循环迭代器一样变量不能在普通 for循环中修改。即使在 for-in 中支持此功能,在这种情况下也没有太大意义。

This is not supported, just as even simple loop iterator variables cannot be modified in a "normal" for loop. Even if this were supported in a for-in, it would not make much sense in this case.

整数是值类型,因此在循环的每次迭代都将实现 s 初始化为数组元素的值,然后将 s 覆盖为 Ct

Integers are value types, so in each iteration of the loop all that would be achieved is that s would be initialised to a value from an element the array and then s overwritten by Ct.

但是数组内容被修改,并且代码的最终结果是否更改。

But the array contents would not be modified and the net effect of the code would be "no change".

要从 for-in 获得期望,您必须能够使用合适的引用类型进行迭代(在在这种情况下,为 PInteger -指向整数的指针)会产生对数组元素的引用,而不是这些元素的值的 副本。然后可以使用取消引用的指针为每个元素分配一个新值:

To get what you expect from a for-in you would have to be able to iterate using a suitable reference type (in this case a PInteger - pointer to integer) yielding references to the array elements, rather than copies of the values of those elements. A new value for each element could then be assigned using the dereferenced pointer:

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;

但是不要感到兴奋-这也不起作用,它只是说明了问题来自引用与值的差异。

But don't get excited - this won't work either, it merely demonstrates the nature of the problem stemming from the difference in a reference vs a value.

这篇关于Delphi:在“ for In”中使用的变量。无法分配!的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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