使用is
关键字检查运行时类型时,在dart中发现了一个奇怪的行为。检查对象是否为某种类型后,可以将其称为方法和字段。不幸的是,这在全局变量的情况下会出现问题。
复制此代码并将其粘贴到DartPad,以查看错误:https://www.dartpad.dev/
class A{
final aVal = 10;
}
class B extends A{
final bVal = 5;
}
void main() {}
void withParam(A a){
if(a is B){
a..aVal..bVal; // no error here
}
}
final A a = B();
void withGlobalScope(){
if(a is B){
// If it checked that 'a' is instance of 'B' why it has no 'bVal' property?
// Why does dart compiler signals this as an error?
// Using the 'as' keyword to cast variable 'a' to type 'B' would solve the issue of course, but it seems unnecessary
a..aVal..bVal; // The getter 'bval' isn't defined for the type 'A'
}
}
有关类型转换和签入飞镖的文档:https://dart.dev/guides/language/language-tour#type-test-operators