简体   繁体   English

如何在delphi中传递一个字符串数组参数

[英]How can I pass array of string a parameter to function in delphi

I have a problem with Delphi. 我有Delphi的问题。

I wrote a function like this: 我写了一个这样的函数:

function MyFunction(arr: array of AnsiString): Boolean;
begin
  //code here
end;

And now, when I pass an array of AnsiString directly into function, like this, everything works perfectly: 而现在,当我将一个AnsiString数组直接传递给函数时,就像这样,一切都很完美:

MyFunction(['one', 'two', 'three']);

But, when I try to store this array like this: 但是,当我尝试像这样存储这个数组时:

var arr: array of AnsiString;

procedure MyProcedure;
begin
  arr[0] := ['one', 'two', 'three'];
  MyFunction(arr[0]);
end;

There is a mismatch error. 存在不匹配错误。

I'm a beginner with Delphi, but this is really confusing. 我是Delphi的初学者,但这真的令人困惑。

Your second example is not functionally identical to the fist example. 你的第二个例子在功能上与第一个例子不同。

The first example is fine. 第一个例子很好。 The function takes an open array as an input parameter, and you are constructing a fixed array of strings directly in that parameter, which is perfectly fine. 该函数将一个开放数组作为输入参数,并且您正在该参数中直接构造一个固定的字符串数组,这非常好。 Any array type can be passed to an open array parameter. 任何数组类型都可以传递给open数组参数。

In the second example, you are declaring a dynamic array of strings, but you are not allocating any memory for the array, and you are trying to assign its first element (which is a single string) to point at a fixed array of strings. 在第二个示例中,您声明了一个动态字符串数组 ,但是您没有为该数组分配任何内存,并且您尝试将其第一个元素(即单个字符串)指定为指向固定的字符串数组。 And then you are trying to pass that element (again, a single string) where an array is expected. 然后你试图传递那个期望数组的元素(再次,一个字符串)。 That is why the code fails to compile. 这就是代码无法编译的原因。

The correct way to write your procedure would like more like this: 编写程序的正确方法更像是这样的:

procedure MyProcedure;
var
  arr: array of AnsiString;
begin
  SetLength(arr, 3);
  arr[0] := 'one';
  arr[1] := 'two';
  arr[2] := 'three';
  MyFunction(arr);
end;

Alternatively: 或者:

procedure MyProcedure;
var
  arr: array of AnsiString;
begin
  arr := ['one', 'two', 'three'];
  MyFunction(arr);
end;

Alternatively: 或者:

type
  TAnsiStringArray = array of AnsiString;

procedure MyProcedure;
var
  arr: TAnsiStringArray;
begin
  arr := TAnsiStringArray.Create('one', 'two', 'three');
  MyFunction(arr);
end;

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

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