我有这个功能:
var _WordApplicationExistsCache: Integer = -1; // Cache result function WordApplicationExists: Boolean; var WordObj: OleVariant; begin if (_WordApplicationExistsCache = -1) then begin Result := False; try try WordObj := CreateOleObject('Word.Application'); WordObj.Visible := False; WordObj.Quit; WordObj := Unassigned; Result := True; except // error end; finally _WordApplicationExistsCache := Ord(Result); // 0;1 end; end else begin Result := Boolean(_WordApplicationExistsCache); end; end;
我试图在应用程序生命周期中只调用一次此函数.我可能根本不会调用这个函数.
这是正确的模式吗?这可以做得更好吗?
编辑:我能想到的另一种方式,在这种情况下是使用2个变量:
var _WordApplicationExistsInitialized: Boolean = False; // Cache result _WordApplicationExistsCacheResult: Boolean; // Undefined ? function WordApplicationExists: Boolean; var WordObj: OleVariant; begin if not _WordApplicationExistsInitialized then begin _WordApplicationExistsInitialized := True; Result := False; try try WordObj := CreateOleObject('Word.Application'); WordObj.Visible := False; WordObj.Quit; WordObj := Unassigned; Result := True; except // error end; finally _WordApplicationExistsCacheResult := Result; end; end else begin Result := _WordApplicationExistsCacheResult; end; end;
关于第一个版本的一些问题是类型转换Boolean
< - > Integer
.如果Boolean
可以初始化为零,那将是完美的(我认为).
对缓存的结果使用TriState类型.
type TTriState = ( tsUnknown, tsFalse, tsTrue ); var _WordApplicationExists : TTriState = tsUnknown; function WordApplicationExists : Boolean; var WordObj: OleVariant; begin if _WordApplicationExists = tsUnknown then try WordObj := CreateOleObject('Word.Application'); WordObj.Visible := False; WordObj.Quit; WordObj := Unassigned; _WordApplicationExists := tsTrue; except _WordApplicationExists := tsFalse; end; Result := _WordApplicationExists = tsTrue; end;