Delphi"Not"运算符返回错误

Don*_*ddy -2 delphi delphi-xe5

此代码用于解析编辑器是否应该是只读的.

Code Snippit

var
TempBool : Boolean;
begin
      TempBool := (fCurrentSelectedItem as TMyCustomObject).CanEdit; //Check whether this object can be edited; TempBool resolves to True
      TempBool := not(TempBool); // Toggle the Boolean value; !!-- TempBool still resolves to True
      curredtEach.properties.ReadOnly := TempBool; // Set the read only property on the editor
end;
Run Code Online (Sandbox Code Playgroud)

TempBool解析为整数,如下所示

      // Integer(TempBool) = 0
      TempBool := (fCurrentSelectedItem as TMyCustomObject).CanEdit; 
      // Integer(TempBool) = -1
      TempBool := not(TempBool); 
      // Integer(TempBool) = -2     
Run Code Online (Sandbox Code Playgroud)

找到这个链接, 但没有帮助.

Delphi版 - XE5

操作系统 - Windows 8.1

在深入研究第三方代码之后,我将这个示例放在一起,以演示如何复制问题.

program TestLongBool;

{$APPTYPE CONSOLE}
{$R *.res}

uses
  System.SysUtils,
  System.Classes,
  System.Variants;

var
  Val: Boolean;
  Temp: Boolean;
  CanEdit: Boolean;

begin
  try
    Byte (Val) := 255;
    // Val resolves to  True | Integer(Val) = -1
    CanEdit := Val;
    // CanEdit resolves to True
    Temp := not CanEdit;
    // Temp is true when expected false | Integer(Temp) = -2
    if Temp then begin
      WriteLn ('Expected false');
    end;
    ReadLn;
  except
    on E: Exception do begin
      WriteLn (E.ClassName, ': ', E.Message);
      ReadLn;
    end;
  end;
end.
Run Code Online (Sandbox Code Playgroud)

Ste*_*nke 9

检查是否CanEdit以二进制方式返回正确的值,因为由于编译器的实现,不仅1被评估为True.但是当否定编译器生成一个xor $01仍然为除1之外的任何正值返回True时.

您可以通过计算此表达式来完成此操作:Integer(TempBool).如果这是除1以外的任何正值,那么CanEdit返回错误.