6
type
   TStaticArray = array[1..10] of integer;
   TDynamicArray = array of integer;

   TMyClass = class(TObject)
   private
      FStaticArray: TStaticArray;
      FDynamicArray: TDynamicArray;
   published
      property staticArray: TStaticArray read FStaticArray write FStaticArray; //compiler chokes on this
      property dynamicArray: TDynamicArray read FDynamicArray write FDynamicArray; //compiler accepts this one just fine
   end;

这里发生了什么?静态数组给出错误,“发布的属性'staticArray'不能是数组类型”但动态数组就可以了吗?我很困惑。任何人都知道这背后的原因,以及我该如何解决它?(不,我不想将我所有的静态数组重新声明为动态数组。它们的大小是有原因的。)

4

5 回答 5

6

Published 声明告诉编译器将信息存储在虚拟方法表中。只能存储某些类型的信息。
已发布属性的类型不能是指针、记录或数组。如果是集合类型,它必须足够小才能存储为整数。
(奥莱利,简而言之,德尔菲)

于 2009-02-27T08:25:05.090 回答
1

你必须有getter和setter。在 D2009 下(没有检查其他版本),getter/setter 的参数由于某种原因不能是 const。?

这在 D2009 下工作正常:

type
  TMyArray = array[0..20] of string;

type
  TMyClass=class(TObject)
  private
    FMyArray: TMyArray;
    function GetItem(Index: Integer): String;
    procedure SetItem(Index: Integer; Value: string);
  public
    property Items[Index: Integer]: string read GetItem write SetItem;
  end;

implementation

function TMyClass.GetItem(Index: Integer): string;
begin
  Result := '';
  if (Index > -1) and (Index < Length(FMyArray)) then
    Result := FMyArray[Index];
end;

procedure TMyClass.SetItem(Index: Integer; Value: string);
begin
  if (Index > -1) and (Index < Length(FMyArray)) then
    FMyArray[Index] := Value;
end;

注意:显然,我通常不会忽略超出范围的索引值。这是一个如何在类定义中创建静态数组属性的快速示例;IOW,这只是一个可编译的示例。

于 2009-02-28T23:00:02.560 回答
0

您可以发布动态数组属性的原因是动态数组被实现为引用或“隐式指针”。它们的工作更像是弦乐,真的。

不能发布静态数组的原因,我不知道。这只是它的制作方式,我猜..

有关动态数组如何工作的更多详细信息,请查看DrBobs 网站

于 2009-02-27T06:59:41.160 回答
0
 TMyClass = class(TObject)
   private
     FStaticArray: TStaticArray;
     FIdx: Integer;
     function  GetFoo(Index: Integer): Integer;
     procedure SetFoo(Index: Integer; Value: Integer);
   public
     property Foo[Index: Integer] : Integer read GetFoo write SetFoo;
   published
     property Idx: Integer read fidx write fidx;
     property AFoo: Integer read GetAFoo writte SetAFoo;
   end;
implementation
function TMyClass.GetAFoo: Integer;
begin
  result := FStaticArray[FIdx];
end;
procedure TMyClass.SetAFoo(Value: Integer);
begin
  FStaticArray[FIdx] := Value;
end;
于 2011-04-18T15:39:32.040 回答
-3

无法发布数组属性。所以下面的代码不起作用。解决方法可能是成功public

   TMyClass = class(TObject)
   private
     FStaticArray: TStaticArray;

     function  GetFoo(Index: Integer): Integer;
     procedure SetFoo(Index: Integer; Value: Integer);
   public
     property Foo[Index: Integer] : Integer read GetFoo write SetFoo;
   end;
于 2009-02-27T02:17:26.907 回答