ClientDataSet的版本兼容性數組
在Delphi的早期版本中,Data這個Variant類型的值內部使用的是AnsiString來存貯的字節流,但我並不肯定Delphi從何時開始,將其改成了Byte數組類型,你能夠經過VarType函數來檢測它的類型。函數
一、將數據集的Data保存到MessagePack協議數據流或文件:spa
var
AMsgPack:TQMsgPack;
begin
AMsgPack:=TQMsgPack.Create;
...
AMsgPack.AsVariant:=ClientDataSet1.Data;
//保存到流AStream中
AMsgPack.SaveToStream(AStream);
//或保存到文件AFileName中
AMsgPack.SaveToFile(AFileName);
...
FreeAndNil(AMsgPack);
end;
二、從MessagePack協議數據流或文件中加載到數據集:
var
AMsgPack:TQMsgPack;
begin
AMsgPack:=TQMsgPack.Create;
//從流AStream中加載
AMsgPack.LoadFromStream(AStream);
//或從文件AFileName中加載
AMsgPack.LoadFromFile(AFileName);
...
ClientDataSet1.Close;
ClientDataSet1.Data:=AMsgPack.AsVariant;
...
FreeAndNil(AMsgPack);
end;
對於早期的版本,咱們須要作一個轉換:對象
一、從AnsiString轉換爲TBytes,而後再賦給AMsgPack。ip
var
S:AnsiString;
ABytes:TBytes;
...
begin
...
//首先將Data賦給一個字符串對象
S:=ClientDataSet1.Data;
//複製到字節流中
SetLength(ABytes,Length(S));
Move(PAnsiChar(S)^,ABytes[0],Length(S));
//用AsBytes替換AsVariant
AMsgPack.AsBytes:=ABytes;
...
end;
二、加載時反過來將字節流反轉成AnsiString
var
S:AnsiString;
ABytes:TBytes;
...
begin
...
//首先將Data賦給一個字符串對象
ABytes:=AMsgPack.AsBytes;
SetLength(S,Length(ABytes));
Move(ABytes[0],PAnsiChar(S)^,Length(ABytes));
//而後將字符串賦給Data就行了。
ClientDataSet1.Data:=S;...
end;