9

我正在尝试使用以下函数来设置作为 var 参数的动态数组的长度。当我尝试编译代码时只有一个错误:

[dcc64 错误] lolcode.dpr(138): E2008 不兼容类型

function execute(var command : array of string) : Boolean;
begin
  // Do something
  SetLength(command,0);
end;
4

2 回答 2

17

You are suffering from a common and fundamental mis-understanding of array parameters. What you have here:

function execute(var command: array of string): Boolean;

is not in fact a dynamic array. It is an open array parameter.

Now, you can pass a dynamic array as a parameter to a function that receives an open array. But you cannot modify the length of the dynamic array. You can only modify its elements.

If you need to modify the length of the dynamic array, the procedure must receive a dynamic array. In modern Delphi the idiomatic way to write that is:

function execute(var command: TArray<string>): Boolean;

If you are using an older version of Delphi that does not support generic arrays then you need to declare a type for the parameter:

type
  TStringArray = array of string;
....
function execute(var command: TStringArray): Boolean;

How should you choose whether to use open array or dynamic array parameters? In my opinion you should always use open arrays if possible to do so. And if not possible, then use dynamic arrays as a final resort. The reason being a function with an open array parameter is more general than one with a dynamic array parameter. For example, you can pass a constant sized array as an open array parameter, but not if the function receives a dynamic array.

于 2012-10-18T16:15:15.543 回答
10

定义一个类型

type
  TStringArray = array of string;

你可以做

function Execute(var StringArray: TStringArray): boolean;
begin
  // Do something
  SetLength(StringArray, 0);
end;
于 2012-10-18T16:03:27.647 回答