Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can some arrays be published but not others?

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;

What's going on here? A static array gives the error, "published property 'staticArray' cannot be of type ARRAY" but dynamic arrays are just fine? I'm confused. Anyone know the reasoning behind this, and how I can work around it? (And no, I don't want to redeclare all my static arrays as dynamic. They're the size they are for a reason.)

like image 782
Mason Wheeler Avatar asked Feb 27 '09 01:02

Mason Wheeler


2 Answers

Published declaration tells the compiler to store information in the virtual method table. Only certain kinds of information can be stored.
The type of a published property cannot be a pointer, record, or array. If it is a set type, it must be small enough to be stored in an integer.
(O'REILLY, DELPHİ IN A NUTSHELL)

like image 62
SimaWB Avatar answered Sep 22 '22 07:09

SimaWB


You have to have getters and setters. Under D2009 (didn't check other versions), the parameters to the getters/setters can't, for some reason, be const. ?

This works fine under 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;

NOTE: I would not typically just ignore Index values out of range, obviously. This was a quick example of how to make static array properties in a class definition; IOW, it's a compilable example only.

like image 20
Ken White Avatar answered Sep 20 '22 07:09

Ken White