Delphi枚举集
我正在尝试过滤我的日志记录。如果选项中有日志(或消息)类型,我想将其发送到日志,否则退出。
编译在“if not MessageType in...”行上失败:
"[dcc32 Error] uMain.pas(2424): E2015 Operator not applicable to this operand type"
我认为基于 Include/Exclude 函数必须是可能的(并且相当简单),我尝试查看但找不到任何地方(即 Include(MySet, llInfo); )。
我的声明如下:
type
TLogLevel = (llDebug, llError, llWarn, llInfo, llException);
TLogOptions = set of TLogLevel;
var
FLogOptions: TLogOptions;
procedure TfrmMain.Log(const s: String; MessageType: TLogLevel;
DebugLevel: Integer; Filter: Boolean = True);
begin
if not MessageType in FLogOptions then
exit;
mmoLog.Lines.Add(s);
end;
回答
由于运算符优先级,您需要在 set 操作周围加上括号。编译器将其解析为if not MessageType,这不是有效的操作。如果在 set 测试周围加上括号,编译器可以正确解析它。
if not (MessageType in FLogOptions) then
这是一个常见问题,并非特定于集合类型。例如,您也可以使用以下 express 得到相同的错误。
if not 1 = 2 and 2 = 3 then
在两个相等测试周围添加括号将更正错误。
if not (1 = 2) and (2 = 3) then
有关更多信息,您可以查看Operator Precedence的文档