这是一个更具体的例子,基于以下方法如何在 Dart NNBD 中检查泛型类型是否可为空? https://stackoverflow.com/q/66240962/.
注意当转换为 JavaScript 时,所有数字都是 IEEE-754 双精度浮点值 https://stackoverflow.com/q/54827376/,所以要区分Dartdouble
/double?
and int
/int?
,我们必须首先检查浮点文字,该文字不能是int
.
void foo<T>() {
if (1.5 is T) {
if (null is T) {
print('double?');
} else {
print('double');
}
} else if (1 is T) {
if (null is T) {
print('int?');
} else {
print('int');
}
} else {
print('something else');
}
}
void main() {
foo<int?>(); // Prints: int?
foo<int>(); // Prints: int
foo<double?>(); // Prints: double?
foo<double>(); // Prints: double
foo<bool>(); // Prints: something else
}
请注意,上述方法不适用于void
or Null
. Null
可以通过检查来处理T == Null
, but T == void
不是有效的语法(类似于T == int?
)。您可以通过将它们作为进行比较的通用函数的类型参数来解决这个问题,因此另一种方法是:
/// Returns true if T1 and T2 are identical types.
///
/// This will be false if one type is a derived type of the other.
bool typesEqual<T1, T2>() => T1 == T2;
void foo<T>() {
if (typesEqual<T, void>()) {
print('void');
} else if (typesEqual<T, Null>()) {
print('Null');
} else if (typesEqual<T, int>()) {
print('int');
} else if (typesEqual<T, int?>()) {
print('int?');
} else if (typesEqual<T, double>()) {
print('double');
} else if (typesEqual<T, double?>()) {
print('double?');
} else {
print('something else');
}
}
void main() {
foo<int?>(); // Prints: int?
foo<int>(); // Prints: int
foo<double?>(); // Prints: double?
foo<double>(); // Prints: double
foo<void>(); // Prints: void
foo<Null>(); // Prints: Null
foo<bool>(); // Prints: something else
}