【发布时间】: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 语句会减少代码并提供更多可用性。
【问题讨论】:
-
我感受到了你的痛苦,C#可以做到这一点docs.microsoft.com/en-us/dotnet/csharp/…
标签: if-statement types dart flutter switch-statement