首页 > 解决方案 > Dart 的双重类型的奇怪行为

问题描述

以下代码输出以下结果:

double firstValue = 1.2;
print('type of firstValue: ${firstValue.runtimeType}'); // double

double secondValue = 1;
print('type of secondValue: ${secondValue.runtimeType}'); // int

print('type of secondValue parsed: ${secondValue.toDouble().runtimeType}'); // int

为什么声明的 double 值被理解为 int 值?即使我进行了显式转换, 1 值仍然是一个 int。

为什么会这样?

标签: dart

解决方案


我假设您使用 dart2js(包括 DartPad)看到了这些结果。

JavaScript 没有单独的intdouble类型;它在任何地方都使用 IEEE-754 双精度浮点值。当 Dart 被转译为 JavaScript 时,Dartintdouble类型都由相同的类型支持,并且转换回 Dart 类型需要启发式,因为类型信息丢失了。

如果您使用 Dart VM 尝试您的代码,您应该会看到预期的结果。


推荐阅读