2011-06-07 61 views
4

串和記錄的是這樣的事情可能與德爾福? (帶有動態數組的字符串和記錄)恆就地陣列中的德爾福

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')]); 

我知道它不能像那樣編譯。只是想問一下是否有一個竅門可以得到類似的東西。

+0

要知道,寫'程序DoSomethingWithStrings(字符串:TStringArray);'將在棧上創建'TStringArray'參數的臨時副本。你最好添加一個'const'這裏,即寫'程序DoSomethingWithStrings(常量字符串:TStringArray);' – 2011-06-07 13:06:52

回答

6

如果你沒有改變你的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",特別是關於「混亂」的部分,以獲取更多信息。

+0

+1這是偉大的。謝謝!我原以爲''數組的字符串'和'TStringArray'是類型等價的,因此可以交換,但這似乎是錯誤的。 – jpfollenius 2011-06-07 10:10:54

+0

這是德爾福不一致的領域之一。在參數列表,你可以不寫'設置TMyEnum'的,你必須聲明'TMyEnums =集TMyEnum'的並使用它 - 同樣的指針等,但使用數組這一切都不同。 :-) – 2011-06-07 10:18:53

+0

的「incosistency」只是在語法,因爲Delphi使用同一個基於上下文兩個不同的含義。 「T:字符串數組」是一個動態數組。 「procedure P(A:字符串數組)」是一個開放數組參數聲明 - 它不是一個動態數組,它接受給定基類型的任何數組。如果你只想傳遞一個給定類型的動態數組,你首先需要一個類型聲明,然後是該類型的一個參數。 – 2011-06-07 11:20:16