本文介绍了为什么我不能返回的字符串数组乱?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

编译器允许我做以下内容:

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']);

然而,将不会允许

However, won't allow

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;

这是为什么?这不是的技术上的同样的事情?

有关这些特定情况下是推荐什么(最有效的)返回字符串的任意阵列的方法是什么?

For these particular scenarios what is the recommended (and most efficient) way of returning an arbitrary array of string?

推荐答案

不,这不是一回事。在

procedure MyProc(const ADynData: array of string);

该参数是一个open数组参数的,这是不一样的事,作为一个普通的动态数组的。在 [..] 语法只能用于创建函数开放数组参数的开放数组。 (否则, [..] 用于指定的设置的在code,如 Font.Style: = [fsBold,fsItalic] ,但只能有序类型作为他们的基地型,所以还是有没有这样的东西'设置字符串')​​

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'.)

在换句话说,它是不可能像你在你的第二个code片断尝试写在code动态数组,

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 dynamic阵列,而 CDynData static阵列,这是两个不同的基本类型。

won't work because TStringDynArray is a dynamic array, while CDynData is a static array, which are two different fundamental types.

这篇关于为什么我不能返回的字符串数组乱?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 12:55