【问题标题】:How to access Switch argument inside a case in Dart如何在 Dart 的案例中访问 Switch 参数
【发布时间】:2019-05-22 14:24:25
【问题描述】:

我想开启动物并采取适当的行动。

switch (animal.runtimeType) {
  case Cat:
    animal.pet();
    break;
  case Crocodile:
    animal.runAway();
    break;
  default:
    print('Not a known animal.');
} 

如果我是 if-chaining 这会起作用,因为作用域会知道 if (animal is Cat){} 块中 animal 的类型。

由于某种原因,switch 语句不是这种情况。 在这种情况下,我会得到错误

The method pet() isn't defined for the class animal

如何在 case 块中使用 case 断言? 我不能使用as,因为我的 CI Lint 不允许它(这是一件好事)并且在案例中使用 If 操作没有意义,因为使用 if-else 语句会减少代码并提供更多可用性。

【问题讨论】:

标签: if-statement types dart flutter switch-statement


【解决方案1】:

我不确定是我没有理解你的问题还是你没有理解问题。

假设您在Cat 中定义了方法pet(),但不在Animal 中,则会发生错误The method pet() isn't defined for the class animal,因为Animal 是通用的。 Animal 不一定是Cat,因此您不能为Animal 调用方法pet(),因为它仅在Cat 内部定义。

如果animal 是一个局部变量,那么在 case 块中进行强制转换是完全安全的。只要您检查了animal 确实是Cat,您就可以可靠地执行(animal as Cat).pet();

【讨论】:

  • 那么为什么animal 的情况下Cat 需要在if 块中不需要进行类型转换?编译器应该知道动物在任何给定情况下的状态,并且不需要再次检查它。除非 if-case 的范围是本地的(并且值不能更改)并且 switch case 是全局的(并且值可能会在块返回之前更改)。
  • @JoelBroström 关于这一点,我无法按照您的示例进行操作。无论我将animal 设置为Cat 还是仅设置为Animal,它都无法通过切换案例并变为默认值:dartpad.dartlang.org/0bf1a2bd12405039c10b0fe1beacccee 我在这里做错了吗?如果是这样,更新的示例将非常有助于理解您的问题。
  • @JoelBroström 因为这些是不同的用法。你的开关和if (animal is Cat) {}不一样,和if (animal.runtimeType == Cat) {}一样。只有当你使用 is 时,Dart 才能自动投射。
  • @HugoPassos 我不能在开关盒中使用is,因为它只能处理== 比较?来自 Kotlin 的 When 语句接缝,就像 Dart switch 语句在各个方面的改进。我错了吗?
  • @JoshuaWade 我应该说这只是用于说明我的问题的伪代码。基本上我想了解的是 switch 和 if 语句的范围有何不同,或者我如何在 switch 中获得与 if-else 链中相同的行为。
猜你喜欢
  • 2020-11-01
  • 1970-01-01
  • 1970-01-01
  • 2022-08-21
  • 2020-12-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-25
相关资源
最近更新 更多