2009-02-27 70 views
5
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「不能是ARRAY類型」,但動態數組很好?我很困惑。任何人都知道背後的原因,以及我如何解決它? (不,我不想重新聲明所有靜態數組都是動態的,它們的大小是有原因的。)爲什麼某些數組可以發佈但不是其他人?

回答

6

發佈聲明告訴編譯器來存儲虛擬方法表的信息。只能存儲特定類型的信息。
已發佈屬性的類型不能是指針,記錄或數組。如果它是一個集合類型,它必須足夠小以存儲在一個整數中。
(O'REILLY,NUTSHELL的DELPHİ)

-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; 
+0

沒有。那也行不通。同樣的錯誤。 – 2009-02-27 02:20:18

+0

如何在不使用TStaticArray作爲屬性的情況下獲得相同的錯誤? – 2009-02-27 02:22:09

+0

Upvoted downvote。 – 2009-02-27 02:43:34

0

您可以發佈動態數組屬性的原因是動態數組實現爲引用或'隱式指針'。他們的工作更像絃樂,真的。

你不能發佈靜態數組的原因,我不知道。這只是它的製作方式,我想..

,詳細瞭解如何動態數組工作,看看DrBobs site

0

你必須有getter和setter。在D2009下(沒有檢查其他版本),由於某些原因,getters/setters的參數不能爲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,這只是一個可編輯的例子。

1
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; 
相關問題