首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> Delphi

Delphi 將 TFont.Style 寫入 INI 檔:字串序列化與反序列化技巧

     編輯:Delphi

TFont.Style 型別為 TFontStyles (集合型別 set of TFontStyle),非單純數值/字串/布林,無法直接由 TIniFile.WriteString/ReadString 處理。本文提供「集合 → 字串 → 集合」雙向轉換的實用函數,支援 fsBold, fsItalic, fsUnderline, fsStrikeOut 四種樣式旗標。

核心轉換邏輯

  • 寫入:逐一檢查 if fsBold in Font.Style then...,拼接成 [fsBold,fsItalic] 格式字串。
  • 讀取:用 Pos 檢查子字串是否存在,重建集合 Style := Style + [fsBold]。

完整程式碼

寫入 INI


uses IniFiles;

procedure SaveFontStyleToIni(const FileName: string; Font: TFont);
var
  Ini: TIniFile;
  S: string;
begin
  Ini := TIniFile.Create(FileName);
  try
    S := '[';
    with Font.Style do
    begin
      if fsBold in Font.Style then
        S := S + 'fsBold';
      if fsItalic in Font.Style then
        S := S + IfThen(S = '[', 'fsItalic', ',fsItalic');
      if fsUnderline in Font.Style then
        S := S + IfThen(S = '[', 'fsUnderline', ',fsUnderline');
      if fsStrikeOut in Font.Style then
        S := S + IfThen(S = '[', 'fsStrikeOut', ',fsStrikeOut');
    end;
    S := S + ']';
    Ini.WriteString('Font', 'Style', S);
  finally
    Ini.Free;
  end;
end;

從 INI 讀取


procedure LoadFontStyleFromIni(const FileName: string; Font: TFont);
var
  Ini: TIniFile;
  S: string;
  Styles: TFontStyles;
begin
  Styles := [];
  Ini := TIniFile.Create(FileName);
  try
    S := Ini.ReadString('Font', 'Style', '[]');
    if Pos('fsBold', S) > 0 then Styles := Styles + [fsBold];
    if Pos('fsItalic', S) > 0 then Styles := Styles + [fsItalic];
    if Pos('fsUnderline', S) > 0 then Styles := Styles + [fsUnderline];
    if Pos('fsStrikeOut', S) > 0 then Styles := Styles + [fsStrikeOut];
    Font.Style := Styles;
  finally
    Ini.Free;
  end;
end;

使用範例


// 存檔
SaveFontStyleToIni('config.ini', FontDialog1.Font);

// 讀檔
LoadFontStyleFromIni('config.ini', FontDialog1.Font);

進階改良:通用集合序列化工具

若專案中有多處需存儲集合型別,可封裝為泛型輔助類 (Delphi 2009+ 支援泛型):


type
  TSetHelper = class helper for Integer // 僅示意,實際需針對具體集合型別
  public
    function ToString: string; // 實作集合→字串
    class function FromString(const S: string): Integer; // 字串→集合
  end;

或參考 System.TypInfo.SetToString / StringToSet (需型別資訊 PTypeInfo) 實作通用版本。

注意事項

  • INI 檔案編碼:Delphi 2009+ TIniFile 為 ANSI,建議改用 TMemIniFile (Unicode) 避免中文亂碼。
  • 字串格式若手動編輯 INI,請維持 [fsBold,fsItalic] 格式,大小寫敏感。
  • 若未來 TFontStyle 擴充新旗標,需同步更新轉換函數。

小結

集合型別序列化為「逗點分隔字串」是 Delphi 傳統技巧。掌握 in 運算子檢查成員、Pos 反向解析、+ 運算子合併集合,即可處理所有 set of Enum 型別的 INI/XML/JSON 存取需求。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved