1

有什么方法可以检查是否在 dart 中为动态变量提供了 getter,而不是在 try catch 块中?

此处的示例
'ThisClass' 中未提供 'v1',因此会出错

class ThisClass{
  bool v2=false;
}

main() {
  dynamic h=ThisClass();
  
  print(h.v1);
}
4

2 回答 2

1

你可以做

class ThisClass {
  bool v2 = false;
}

main() {
  dynamic h = ThisClass();
  if (h is ThisClass) {
    print(h.v2);
  }
}
于 2020-06-30T07:15:08.580 回答
0

您可以尝试访问try块中的变量并捕获结果错误(如果它不存在):

try {
  print(h.v1);
} catch (e) {
  // Handle the error
}
于 2020-06-30T06:05:31.963 回答