为什么我可以在Delphi中将Single除以Variant,它有什么用?
Why can I divide Single by Variant in Delphi, and what is it for?
我惊讶地发现,浮点值可以除以 Delphi 中的 Variant。可以做什么的简单示例:
var
v: Variant;
begin
v := 2.3;
Tag := 5.1 div v; // 2
Tag := 5.1 mod v; // 1
Tag := 5.1 div 2; // [dcc32 Error] E2015 Operator not applicable to this operand type
Tag := 5.1 mod 2; // [dcc32 Error] E2015 Operator not applicable to this operand type
end;
看起来 Delphi 在执行 div
/mod
操作之前将左侧部分和右侧部分四舍五入。
我希望上面的代码在所有 4 行的编译时都产生错误,因为我的理解是 div/mod 无论如何都不适用于浮点值。显然不是这样。
为什么我可以在Delphi中将Single除以Variant,它需要做什么?
If an expression combines variants with statically-typed values, the statically-typed values are automatically converted to variants.
这意味着 float 类型的文字首先被转换为变体。
然后在执行 div/mod 操作之前,将两个变体隐式转换为整数值以匹配运算符。
Variant Type Conversions
..and what is it needed for?
只是为了尽可能多才多艺,全面支持OLE。
我惊讶地发现,浮点值可以除以 Delphi 中的 Variant。可以做什么的简单示例:
var
v: Variant;
begin
v := 2.3;
Tag := 5.1 div v; // 2
Tag := 5.1 mod v; // 1
Tag := 5.1 div 2; // [dcc32 Error] E2015 Operator not applicable to this operand type
Tag := 5.1 mod 2; // [dcc32 Error] E2015 Operator not applicable to this operand type
end;
看起来 Delphi 在执行 div
/mod
操作之前将左侧部分和右侧部分四舍五入。
我希望上面的代码在所有 4 行的编译时都产生错误,因为我的理解是 div/mod 无论如何都不适用于浮点值。显然不是这样。
为什么我可以在Delphi中将Single除以Variant,它需要做什么?
If an expression combines variants with statically-typed values, the statically-typed values are automatically converted to variants.
这意味着 float 类型的文字首先被转换为变体。
然后在执行 div/mod 操作之前,将两个变体隐式转换为整数值以匹配运算符。 Variant Type Conversions
..and what is it needed for?
只是为了尽可能多才多艺,全面支持OLE。