2013-01-15 42 views
4

我需要移動存儲的字節數組一套位於從TList記錄中的數據,但我得到這個錯誤如何使用移動過程填充TList <T>元素?

E2197常量對象不能作爲變量參數傳遞

此代碼重現此問題。

uses 
    System.Generics.Collections, 
    System.SysUtils; 

type 
    TData = record 
    Age : Byte; 
    Id : Integer; 
    end; 

//this code is only to show the issue, for simplicity i'm filling only the first 
//element of the TList but the real code needs fill N elements from a very big array. 
var 
    List : TList<TData>; 
    P : array [0..1023] of byte; 
begin 
    try 
    List:=TList<TData>.Create; 
    try 
     List.Count:=1; 
     //here i want to move the content of the P variable to the element 0 
     Move(P[0],List[0], SizeOf(TData)); 

    finally 
     List.Free; 
    end; 

    except 
    on E: Exception do 
     Writeln(E.ClassName, ': ', E.Message); 
    end; 
end. 

我怎樣才能一個緩衝器的內容複製到一個元素的TList

+0

定義「需要」?看來你應該說「想要」。 –

回答

4

在XE2,用於TList<T>內部存儲是不透明的和隱藏的。通常情況下,您無法訪問它。所有對列表元素的訪問都被複制 - 對底層存儲的引用不可用。所以你不能使用Move來接受它。如果你想要一個可以接受的結構,你應該考慮一個動態數組,TArray<T>

你總是可以使用執行類助手的技巧,這將暴露私人變量FItems。這很哈克,但會做你的問題。

type 
    __TListTData = TList<TData>; 
    //defeat E2086 Type 'TList<T>' is not yet completely defined 

type 
    TListTDataHelper = class helper for TList<TData> 
    procedure Blit(const Source; Count: Integer); 
    end; 

procedure TListTDataHelper.Blit(const Source; Count: Integer); 
begin 
    System.Move(Source, Pointer(FItems)^, Count*SizeOf(Self[0])); 
end; 

我猜你可能想要把一些參數TListTDataHelper.Blit檢查,但我會留給你。

如果您使用的是XE3,則可以使用List屬性訪問TList<T>的私有存儲。

Move(P, Pointer(List.List)^, N*SizeOf(List[0])); 

如果您不需要做塊,並且可以使用一個for循環,然後像這樣做:

type 
    PData = ^TData; 
var 
    i: Integer; 
    Ptr: PData; 
.... 
List.Count := N; 
Ptr := PData(@P); 
for i := 0 to List.Count-1 do 
begin 
    List[i] := Ptr^; 
    inc(Ptr); 
end; 

但我理解你的問題,你要避免使用此選項。

+0

99.99%的時間是聰明和完全不好的想法。請想想跟在你後面的人,並且必須維護包含這個醜陋的混合物的代碼,並且永遠不要這樣做。 –

+0

@Warren是的,我想我會使用for循環! –

1

而不是使用Move(),請嘗試使用TList<T>.Items[]屬性setter,而不是讓編譯器和RTL處理複製給你的:

type 
    PData = ^TData; 
    ... 

List[0] := PData(@P[0])^; 
+0

問題描述了一個願望,讓N個元素一氣呵成 –

+0

儘管如此,OP還是要求一支加載的槍,並希望用它來做一個更適合蒼蠅拍的工作,並指出在腳下自己射擊是在我看來,這是一件壞事,建議他們這樣做是可取的。 –