“双数组”之间的区别和TDoubleDynArray [英] Difference between "array of double" and TDoubleDynArray
问题描述
System.Types
单位声明数组类型:
TDoubleDynArray = array of Double;
如果我声明一个方法:
procedure func (x : TDoubleDynArray)
我注意到参数 x
的行为就像一个 var
参数,即我可以更改 x
在方法中,我会看到方法之外的变化。
I notice that the argument x
acts like a var
argument, ie I can change x
inside the method and I'll see the changes reflected outside the method.
但是当我使用
procedure func (x : array of double)
, x
中的任何更改均保留在 func
中。虽然 TDoubleDynArray
似乎被声明为双重的数组,但它的行为与我自己的
双重数组
。这是什么解释?
As expected, any changes in x
stays in func
. Although TDoubleDynArray
appears to be declared as an array of double
, it behaves differently from my own array of double
. What is the explanation for this?
更新:我注意到,如果我声明自己的类型 TMyArray =数组double
然后我得到与 TDynamicDynArray
相同的行为。这是否与基本数组类型之间的区别有关?
Update: I noticed that if I declare my own type TMyArray = array of double
then I get the same behavior as TDynamicDynArray
. Is this something to do with a difference between basic array types?
测试代码如下
program Project1;
{$APPTYPE CONSOLE}
{$R *.res}
uses System.Types;
var
x : TDoubleDynArray;
y : array of double;
procedure func1 (x : TDoubleDynArray);
begin
x[0] := -999.123;
end;
procedure func2 (y : array of double);
begin
y[0] := -999.123;
end;
begin
setLength (x, 10);
func1 (x);
writeln ('TDoubleDynArray: ', x[0]);
setLength (y, 10);
y[0] := 0;
func2 (y);
writeln ('array of double: ', y[0]);
Readln;
end.
推荐答案
procedure func1 (x : TDoubleDynArray);
函数参数是一个动态数组。这是一个参考类型。这意味着函数参数 x
是对数组的引用。其结果是, func1
中的数组元素的更改会更改调用者的数组。
The function argument is a dynamic array. That is a reference type. That means that the function argument x
is a reference to the array. A consequence of that is that changes to the elements of the array inside func1
change the caller's array.
procedure func2 (y : array of double);
函数参数是一个打开数组参数。虽然它超载了语法的数组,但它与动态数组是一个不同的野兽。因为这个打开的数组是通过值传递的,所以数组的一个副本被传递给函数,所以这个函数的修改对于调用者是不可见的。
The function argument is an open array parameter. Although it overloads the array of
syntax it is quite a different beast from a dynamic array. Because this open array is passed by value, a copy of the array is passed to the function, and so modifications made by the function are not visible to the caller.
值得指出的是,由于您通过值传递了 y
,将传递数组的副本。对于较大的阵列,效率较低。通常,应该避免通过值开放数组。使用 var
或 const
打开数组参数。同样的建议适用于其他大型类型,如固定长度的数组和记录。
It's worth pointing out that, because you passed y
by value, a copy of the array is passed. That is inefficient, more so for larger arrays. As a rule, by value open arrays should be avoided. Use either var
or a const
open array parameters. The same advice applies to other large types, like fixed length arrays and records.
打开数组参数是一个无休止的混乱来源。我建议您阅读我链接的文档,以及Rudy关于此主题的文章:打开数组参数和const数组。
Open array parameters are an endless source of confusion. I recommend that you read the documentation that I linked to, and Rudy's article on the subject: Open array parameters and array of const.
这篇关于“双数组”之间的区别和TDoubleDynArray的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!