【问题标题】:Constant in-place array of strings and records in DelphiDelphi中字符串和记录的常量就地数组
【发布时间】:2011-06-07 09:35:14
【问题描述】:

Delphi 可以实现这样的功能吗? (带有字符串和记录的动态数组)

type
  TStringArray = array of String;
  TRecArray = array of TMyRecord;

procedure DoSomethingWithStrings(Strings : TStringArray);
procedure DoSomethingWithRecords(Records : TRecArray);
function BuildRecord(const Value : String) : TMyRecord;

DoSomethingWithStrings(['hello', 'world']);
DoSomethingWithRecords([BuildRecord('hello'), BuildRecord('world')]);

我知道它不会这样编译。只是想问是否有一个技巧可以得到类似的东西。

【问题讨论】:

  • 请注意,写入procedure DoSomethingWithStrings(Strings : TStringArray); 将在堆栈上创建TStringArray 参数的临时副本。您最好在此处添加const,即写procedure DoSomethingWithStrings(const Strings : TStringArray);

标签: arrays delphi delphi-xe


【解决方案1】:

如果您不必更改 DoSomethingWith* 例程中的数组长度,我建议使用开放数组而不是动态数组,例如像这样:

procedure DoSomethingWithStrings(const Strings: array of string);
var
  i: Integer;
begin
  for i := Low(Strings) to High(Strings) do
    Writeln(Strings[i]);
end;

procedure DoSomethingWithRecords(const Records: array of TMyRecord);
var
  i: Integer;
begin
  for i := Low(Records) to High(Records) do
    Writeln(Records[i].s);
end;

procedure Test;
begin
  DoSomethingWithStrings(['hello', 'world']);
  DoSomethingWithRecords([BuildRecord('hello'), BuildRecord('world')]);
end;

请注意参数列表中的array of string - 而不是TStringArray!更多信息请参阅文章"Open array parameters and array of const",尤其是关于“混淆”的部分。

【讨论】:

  • +1 这很棒。谢谢!我原以为array of StringTStringArray 是类型等价的,因此可以互换,但这似乎是错误的。
  • 这是 Delphi 不一致的地方之一。您不能在参数列表中写入 set of TMyEnum,您必须声明 TMyEnums = set of TMyEnum 并使用它来代替 - 与指针等相同。但对于数组,一切都不同。 :-)
  • “不一致”只是在语法中,因为 Delphi 根据上下文使用相同的具有两种不同含义的。 “T:array of string”是一个动态数组。 “procedure P(A: array of string)”是一个开放的数组参数声明——它不是一个动态数组,它接受给定基类型的任何数组。如果你想明确地只传递给定类型的动态数组,你需要先声明一个类型,然后是该类型的参数。
  • 可能“混淆”是更好的表达方式:如果您使用 Delphi 有时会发现 P(AMyEnums: set of TMyEnum) 不起作用,并且您必须显式声明一个类型。现在如果你需要传递一个数组,你会本能地使用显式类型,即使它是错误的。
  • IIRC 这是因为在 Pascal 中,两种不同的 var/param 类型声明无论它们多么相同,它们都不兼容,因此 "A: array[0..1] of Bye; B: array[0 ..1]字节;" A 和 B 不是赋值兼容的,它仅在首先声明一个类型然后 A 和 B 声明为相同类型时才有效。参数也会发生这种情况。开放数组参数是对 Pascal 规则的 Delphi 增强,允许在将数组传递给过程时更加灵活,并且 IIRC 它们早于动态数组
猜你喜欢
  • 1970-01-01
  • 2011-07-11
  • 2011-12-02
  • 1970-01-01
  • 1970-01-01
  • 2010-12-21
  • 2015-09-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多