为什么不能在as表达式中使用Object.runtimeType?

问题描述 投票:1回答:1

根据Object.runtimeType的Dart文档,该字段的类型是Type。这令人困惑,因为我从编译器收到一个错误,抱怨这个字段不是一个类型。

请参阅以下示例代码:

final double first = 1.0;
final int second = 2;

final third = second as double;       // works fine, unlike declaration below.
assert(first.runtimeType == double);  // true

final fourth = second as first.runtimeType;

最后一行抛出了这个编译时错误:

名称“first.runtimeType”不是类型,因此不能在“as”表达式中使用。

示例代码显示first.runtimeType == double,所以不会遵循_ as first.runtimeType相当于_ as double

dart
1个回答
2
投票

我认为它实际上很简单,runtimeType仅在RunTime上可用,并且无法由编译器进行静态分析。

© www.soinside.com 2019 - 2024. All rights reserved.