利用 Delphi 10.1+ 的進階記錄型別特性(支援方法、屬性、運算子多載),實作一個功能完整的字串二維表結構 TSta,支援分隔符自訂、檔案 IO、索引存取等豐富功能。
unit STA;
interface
uses System.SysUtils, System.Classes;
type
TSta = record
private
FSeparator: Char;
FArr: TArray<TArray<string>>;
function GetItem(i,j: Integer): string;
procedure SetItem(i,j: Integer; Value: string);
function GetRow(i: Integer): string;
procedure SetRow(i: Integer; Value: string);
procedure SetSeparator(const Value: Char);
function GetRowCount: Integer;
procedure SetRowCount(const Value: Integer);
public
constructor Create(const aStr: string; const aSeparator: Char = ';'); overload;
class operator Explicit(const aStr: string): TSta;
class operator Implicit(const aStr: string): TSta;
function ToString: string;
procedure Clear;
procedure LoadFromFile(const aFileName: string; aEncoding: TEncoding = nil);
procedure SaveToFile(const aFileName: string; aEncoding: TEncoding = nil);
property Separator: Char read FSeparator write SetSeparator;
property RowCount: Integer read GetRowCount write SetRowCount;
property Items[i,j: Integer]: string read GetItem write SetItem; default;
property Rows[i: Integer]: string read GetRow write SetRow;
end;
implementation
{ TSta 方法實作略... 核心邏輯包含:
- 建構函式解析字串為二維陣列
- 索引器支援邊界檢查與自動擴展
- 分隔符動態切換
- 檔案讀寫支援編碼指定
- 隱式/顯式字串轉換運算子 }
end.
uses STA;
procedure TForm1.Button1Click(Sender: TObject);
var S: TSta; str: string;
begin
{ 從字串隱式/顯式轉換建立 }
S := 'AAA;BBB;CCC' + sLineBreak + '111;222;333';
str := S[0,0]; { AAA }
str := S[1,2]; { 333 }
str := S[9,9]; { 越界讀取回傳空字串 }
str := S.Rows[0]; { AAA;BBB;CCC }
str := S.Rows[1]; { 111;222;333 }
str := S.ToString; { 完整表格字串 }
S.Separator := '&'; { 更換分隔符 }
str := S.Rows[1]; { 111&222&333 }
ShowMessage(str);
end;
procedure TForm1.Button2Click(Sender: TObject);
var S: TSta; str: string;
begin
{ 索引賦值自動擴展陣列 }
S[0,0] := 'aaa'; S[0,1] := 'bbb'; S[0,2] := 'ccc';
S[2,2] := 'zzz'; { 中間空列自動填充 }
str := S.ToString; { aaa;bbb;ccc / /;;zzz }
S.Rows[1] := '111;222;333';
str := S.ToString; { aaa;bbb;ccc / 111;222;333 / ;;zzz }
end;
procedure TForm1.Button3Click(Sender: TObject);
const nFileName = 'c:\temp\staTest.txt';
var S: TSta; str: string;
begin
S[0,0] := 'aaa'; S[0,1] := 'bbb'; S[0,2] := 'ccc';
S[1,0] := '111'; S[1,1] := '222'; S[1,2] := '333'; S[1,3] := '444';
S.SaveToFile(nFileName); { 儲存到檔案 }
S.Clear;
str := S[0,0]; { 空 }
S.LoadFromFile(nFileName); { 從檔案讀取 }
str := S[0,0]; { aaa }
str := S.Rows[0]; { aaa;bbb;ccc }
end;
Items 為 default property,可直接 S[i,j] 存取Separator 即時影響輸出格式這個實作展示了現代 Delphi 記錄型別的強大表達能力,將複雜的二維表操作封裝為直觀、安全的介面。