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]。
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;
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) 實作通用版本。
TIniFile 為 ANSI,建議改用 TMemIniFile (Unicode) 避免中文亂碼。[fsBold,fsItalic] 格式,大小寫敏感。TFontStyle 擴充新旗標,需同步更新轉換函數。集合型別序列化為「逗點分隔字串」是 Delphi 傳統技巧。掌握 in 運算子檢查成員、Pos 反向解析、+ 運算子合併集合,即可處理所有 set of Enum 型別的 INI/XML/JSON 存取需求。