为什么我不能返回任意数组的字符串? [英] Why can't I return arbitrary array of string?
问题描述
编译器允许我执行以下操作:
The compiler allows me to do the following:
procedure MyProc(const ADynData: array of string);
或
procedure MyProc(const ADynData: TStringDynArray);
并传递如下所示的任意数据:
and pass arbitrary data like so:
MyProc(['Data1', 'Data2']);
但是,不允许
function MyFunc: TStringDynArray;
....
function MyFunc: TStringDynArray;
begin
Result := ['Data1', 'Data2'];
end;
或
function MyFunc: TStringDynArray;
const
CDynData: array[0..1] of string = ('Data1', 'Data2');
begin
Result := CDynData;
end;
为什么是这样?对于这些特定的场景,什么是返回任意数组的推荐(最有效)的方法是什么?这个技术上不是这样吗?
Why is this? Isn't this technically the same thing?
的字符串?
推荐答案
不,这不一样。在
procedure MyProc(const ADynData: array of string);
参数是 打开数组参数 ,这与普通动态数组不一样 em>。 [..]
语法只能用于在函数的开放数组参数中创建开放数组。 (否则, [..]
用于在代码中指定集,例如 Font.Style:= [fsBold ,fsItalic]
。但设置只能有序列类型作为它们的基本类型,所以仍然没有这样的东西,如set of string。)
the argument is an open array parameter, which is not the same thing as an 'ordinary' dynamic array. The [..]
syntax can only be used to create open arrays in open array parameters of functions. (Otherwise, [..]
is used to specify sets in code, such as Font.Style := [fsBold, fsItalic]
. But sets can only have ordinal types as their 'base types', so there is still no such thing as 'set of string'.)
换句话说,不可能写代码中的一个动态数组,就像您在第二个代码片段中尝试一样,
In other words, it is not possible to write a dynamic array in code like you try in your second code snippet,
function MyFunc: TStringDynArray;
begin
result := ['Data1', 'Data2']; // Won't work.
end;
然而,在新版本的Delphi中,几乎可以:
However, in new versions of Delp it is almost possible:
type
TStringDynArray = array of string;
function MyFunc: TStringDynArray;
begin
result := TStringDynArray.Create('A', 'B');
end;
最后,
function MyFunc: TStringDynArray;
const
CDynData: array[0..1] of string = ('Data1', 'Data2');
begin
result := CDynData;
end;
将无法正常工作,因为 TStringDynArray
是动态数组,而 CDynData
是 static 数组,这是两种不同的基本类型。
won't work because TStringDynArray
is a dynamic array, while CDynData
is a static array, which are two different fundamental types.
这篇关于为什么我不能返回任意数组的字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!