简体   繁体   English

动态数组作为Delphi 7中的可选参数

[英]Dynamic Array as optional parameter in Delphi 7

Is it possible to pass to a function or procedure a dynamic array as optional parameter ? 是否可以将动态数组作为可选参数传递给函数或过程? If yes, how ? 如果有,怎么样?

I have tried in this way : 我试过这样的方式:

procedure testp (str : string; var arr : StringArray = nil);
begin
    str := 'Ciao Alessio !';
    SetLength(arr, 2);
    arr[0] := 'Ale';
    arr[1] := 'Ale';
end;

but it gives : default parameter 'arr' must be by-value or const . 但它给出: default parameter 'arr' must be by-value or const

I'm using Delphi 7, but if not possible with Delphi 7, is it possible with newer version of Delphi or Free Pascal ? 我正在使用Delphi 7,但如果不能使用Delphi 7,是否可以使用较新版本的Delphi或Free Pascal?

Default parameters can only be specified for const or by value parameters. 只能为const或value参数指定默认参数。 They cannot be specified for var parameters. 无法为var参数指定它们。

To achieve the caller flexibility you are looking for you'll need to use overloads. 为了实现调用者的灵活性,您需要使用重载。

procedure foo(var arr: StringArray); overload;
begin
  .... do stuff
end;

procedure foo; overload;
var
  arr: StringArray;
begin
  foo(arr);
end;

The error message means exactly what it says, and it has nothing to do with the parameter being a dynamic array. 错误消息意味着它所说的内容,它与作为动态数组的参数无关。 The compiler would have rejected that code no matter what type the parameter had because you're not allowed to give default values for parameters passed by reference. 无论参数具有什么类型,编译器都会拒绝该代码,因为您不允许为通过引用传递的参数提供默认值。

To make an optional reference parameter, use overloading to give two versions of the function. 要创建可选的参考参数,请使用重载来提供该函数的两个版本。 Change your current function to receive its parameter by value or const, as the compiler advises, and then declare another function without that parameter, as follows: 更改当前函数以按值或const接收其参数(如编译器所建议),然后声明另一个不带该参数的函数,如下所示:

procedure testp (str : string);
var
  arr: StringArray;
begin
  testp(str, arr);
end;

That is, declare a dummy parameter and pass it to the "real" function. 也就是说,声明一个伪参数并将其传递给“真实”函数。 Then simply throw away the value it returns. 然后简单地扔掉它返回的值。

If calculation of the reference value is expensive, then the implementation of the one-parameter version of testp will instead duplicate more of the code from the two-argument version. 如果参考值的计算是昂贵的,那么testp的单参数版本的testp将从双参数版本复制更多代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM