本文介绍了为什么将真正的变量布尔值转换为整数时变为-1?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我意识到,当转换为<$ c $时,不应期望真正的 Boolean s成为 1 c>整数,纯粹是因为它们变成非< 0

I realise that one should not expect true Booleans to become 1 when cast to an Integer, purely that they become non-0.

但是,结果变化取决于变量是 Variant (但 varBoolean )还是 Boolean

However, the result changes depending on whether the variable is a Variant (but varBoolean) or a Boolean.

请考虑以下内容:

I := Integer(true);

I 现在为 1

但是...

var
  I: Integer;
  V: Variant;
begin
  V := true;
  I := Integer(V);
end;

I 现在为 -1

当然,如果我将V强制转换为 Boolean 将结果 Boolean 转换为 Integer I 变为 -1

Of course, if I cast V to a Boolean before casting the resulting Boolean to an Integer, I becomes -1.

但是我很奇怪为什么。

是因为存储 Boolean 的方式(例如 1 位),并且当转换为 Integer 时,Delphi会执行转换,而将 Variant 转换为<$ c $时不会发生这种转换。 c> Integer ?

Is this because of the way that Booleans are stored (say as 1 bits), and when casting to an Integer, Delphi performs a conversion, which does not occur when casting a Variant to Integer?

我只提出这一点,因为如果您习惯使用真正的 Boolean 强制转换为 1 ,使用共享 varBoolean 股份制可能很危险 VarType()-案例中的varInteger

I only bring this up, because if you are used to a true Boolean casting to 1, it can be dangerous to have varBoolean share case with varInteger in a VarType()-case.

例如:

case VarType(V) of 
  varInteger, varBoolean: I := Integer(V);
end;

行为不会像人们期望的那样。

Would not behave as one might expect.

推荐答案

该行为的确符合预期。 varBoolean 类型对应于 VT_BOOL 。 是这样的:

The behaviour is indeed as expected. The varBoolean type corresponds to VT_BOOL. Which is documented like this:

布尔值。 True为-1,false为0。

A Boolean value. True is -1 and false is 0.

您还说过,Delphi的布尔值存储为1位。这不是真的。它们存储在单个字节的8位中。我想关键在于, VT_BOOL 变体不包含Delphi Boolean VT_BOOL 变体完全是另一种野兽,最早可追溯到VB。 Raymond Chen在这里对此进行了一些讨论:。

You also say that Delphi's boolean is stored as 1 bit. That's not actually true. They are stored in a single byte, 8 bits. I suppose the key point is that a VT_BOOL variant does not contain a Delphi Boolean. The VT_BOOL variant is a different beast altogether, dating originally from VB. Raymond Chen discusses this a little here: BOOL vs. VARIANT_BOOL vs. BOOLEAN vs. bool.

这篇关于为什么将真正的变量布尔值转换为整数时变为-1?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-19 15:46