无法使用 TMemoryStream 读取布尔值
Cannot read boolean value with TMemoryStream
我正在尝试使用像这样的简单代码行读取布尔值:ReadBuffer(Result, 1)。
阅读后,结果为真。然而
Result:= not Result
不会 'switch' 值 false。
我在这里显然犯了一个基本错误。
完整代码:
TYPE
TCMemStream= class(TMemoryStream)
public
function ReadBoolean: Boolean;
end;
function TCMemStream.ReadBoolean: Boolean;
begin
ReadBuffer(Result, 1);
Result:= NOT Result; <-------- after executing this line, Result has the same value
Result:= false; <----- this works
end;
Boolean
的有效值为 0 和 1。如果将不同的值放入 Boolean
变量,则未来的行为是不确定的。
您应该读入字节变量 b
并将 b <> 0
赋值给 Boolean
。或者通过将字节转换为 ByteBool
来进行清理。或者您可以选择验证从文件中读取的值并拒绝 0
和 1
以外的任何值。
我正在尝试使用像这样的简单代码行读取布尔值:ReadBuffer(Result, 1)。
阅读后,结果为真。然而
Result:= not Result
不会 'switch' 值 false。
我在这里显然犯了一个基本错误。
完整代码:
TYPE
TCMemStream= class(TMemoryStream)
public
function ReadBoolean: Boolean;
end;
function TCMemStream.ReadBoolean: Boolean;
begin
ReadBuffer(Result, 1);
Result:= NOT Result; <-------- after executing this line, Result has the same value
Result:= false; <----- this works
end;
Boolean
的有效值为 0 和 1。如果将不同的值放入 Boolean
变量,则未来的行为是不确定的。
您应该读入字节变量 b
并将 b <> 0
赋值给 Boolean
。或者通过将字节转换为 ByteBool
来进行清理。或者您可以选择验证从文件中读取的值并拒绝 0
和 1
以外的任何值。