如何在 Delphi Syndey 10.4 中正确拆分逗号分隔的文本?

How do I properly split comma delimited text in Delphi Syndey 10.4?

我正在将代码从 Lazarus 转换为 Delphi 10.4 Sydney 并且有一行抛出错误:

// Split line and put it into a new array, txtDataArray
txtDataArray := txtToParse.Split(['.', ',', '!'], TStringSplitOptions.ExcludeEmpty);

txtToParse 是逗号分隔的文本变量。

我该如何正确编写才能在 Delphi 10.4 Sydney 中工作?

我试过了,但收到一条错误消息:

Incompatible Types - a Dynamic Array and System TArray<System String> at line 340:

var下我有:

// For splitting
charArray : Array[0..2] of Char;
txtToParse : String;
txtArray : array of String;

然后在主函数中我有:

// Split line and put it into a new array, txtArray
charArray[0] := '.';
charArray[1] := ',';
charArray[2] := '!';
txtArray := txtToParse.Split(charArray);

我怎样才能让它在 Delphi 10.4 Sydney 中工作?

您需要更改此声明:

txtArray : array of String;

为此:

txtArray : TArray<String>;

原因在文档中有详细解释:

Type Compatibility and Identity (Delphi)

特别是:

Array Types and Assignments

Arrays are assignment-compatible only if they are of the same type. Because the Delphi language uses name-equivalence for types, the following code will not compile.

var
  Int1: array[1..10] of Integer;
  Int2: array[1..10] of Integer;
...
Int1 := Int2; 

To make the assignment work, declare the variables as:

var
  Int1, Int2: array[1..10] of Integer; 

or:

type
  IntArray = array[1..10] of Integer;
var
  Int1: IntArray; Int2: IntArray;

Overloads and Type Compatibility in Generics

Two non-instantiated generics are considered assignment compatible only if they are identical or are aliases to a common type.

Two instantiated generics are considered assignment compatible if the base types are identical (or are aliases to a common type) and the type arguments are identical.

在 FreePascal 中,Split() returns TStringArrayarray of string 的普通别名,因此与 array of string 的赋值兼容变量。

但在 Delphi、Split() returns 中有一个 TArray<String>,这是 array of T 的通用别名,其中 Tstring,因此它是一个独特的通用类型,因此与 array of String 变量不兼容,仅与 TArray<String> 变量兼容。