【问题标题】:Delphi open array as property index in indexed propertyDelphi 开放数组作为索引属性中的属性索引
【发布时间】:2021-12-15 13:05:45
【问题描述】:

是否可以使用开放数组作为索引属性的索引类型?

unit OpenArrayAsPropertyIndex;

interface

type

  TFoo = class
  private
    function getBar(Index: array of Integer): String;
  public
    // [DCC Error]: E2008 Incompatible types
    property Bar[Index: array of Integer]: String read getBar;
  end;

implementation

function TFoo.getBar(Index: array of Integer): String;
begin

end;

end.

属性 getter 是通过在 IDE 中按 Ctl+Shift+C 生成的,但此代码无法编译并给出错误“E2008 不兼容类型”。那么,这是语言限制,还是 getter 的正确参数签名是什么?

【问题讨论】:

  • 我认为这无关紧要,但请尝试添加const
  • getBar(const Index: array of Integer).
  • 反问:代码应该如何使用这样的属性?你对此有答案吗?
  • @Uli Gerhardt:“const”不起作用,它给出了同样的错误。
  • @AmigoJack:我只是在玩。但显然它应该用作 "s := Foo.Bar[[1,2,3]];"

标签: delphi indexed-properties open-array-parameters


【解决方案1】:

使用 System.Types 中的 TIntegerDynArray 或类似的自声明类型,而不是 array of Integer

type
  TIntArray = array of Integer;
  TFoo = class
  private
    function getBar(Index: TIntArray): String;
  public
    property Bar[Index: TIntArray]: String read getBar;
  end;

function TFoo.getBar(Index: TIntArray): String;
begin

end;

【讨论】:

  • TArray<Integer>
  • 但这是一个动态数组,不是一个开放数组。 (考虑到他上面的评论,这对 OP 来说可能没问题。)
  • 开放数组只允许作为过程等的参数。很可能不包括索引属性。我的回答是否有效取决于预期用途。
猜你喜欢
  • 2012-09-28
  • 1970-01-01
  • 2011-01-30
  • 1970-01-01
  • 2023-03-16
  • 1970-01-01
  • 2013-06-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多